Use js to export data to excel/csv

method

const download = (str,data) => {
    
    
    // 增加\t为了不让表格显示科学计数法或者其他格式
    for(let i = 0 ; i < data.length ; i++ ){
    
    
        for(const key in data[i]){
    
    
            str+=`${
    
    data[i][key] + '\t'},`;
        }
        str+='\n';
    }
    // encodeURIComponent解决中文乱码
    const uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
    // 通过创建a标签实现
    const link = document.createElement("a");
    link.href = uri;
    // 对下载的文件命名
    link.download =  "下载数据.csv";
    link.click();
}

Comment

  1. This method receives two parameters
    ① The first parameter is the title of each cell, separated by commas
    ② The second is the specific data, which is an array, which is saved using json data.
    ③ When storing, the values ​​in each json data will be stored in order, so make sure that the data sequence is correct.

Complete experiment code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p style="font-size: 20px;color: red;">使用a标签方式将json导出csv文件</p>
<button id="download">导出</button>
<script>
    document.getElementById("download").addEventListener('click',function(){
    
    
        download(str,data);
    })
    // 列标题,逗号隔开,每一个逗号就是隔开一个单元格
    str = `名称,经度,纬度\n`;
    // 要导出的json数据
    data = [
        {
    
    
            name:'监测站1',
            lon:'123',
            lat:'312'
        },
        {
    
    
            name:'监测站2',
            lon:'123',
            lat:'312'
        },
        {
    
    
            name:'监测站3',
            lon:'123',
            lat:'312'
        }
    ]
    const download = (str,data) => {
    
    
        // 增加\t为了不让表格显示科学计数法或者其他格式
        for(let i = 0 ; i < data.length ; i++ ){
    
    
            for(const key in data[i]){
    
    
                str+=`${
    
    data[i][key] + '\t'},`;
            }
            str+='\n';
        }
        // encodeURIComponent解决中文乱码
        const uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
        // 通过创建a标签实现
        const link = document.createElement("a");
        link.href = uri;
        // 对下载的文件命名
        link.download =  "下载数据.csv";
        link.click();
    }
</script>
</body>
</html>

Guess you like

Origin blog.csdn.net/KaiSarH/article/details/109096252