美文网首页
Javascript 数组生成 CSV 文件

Javascript 数组生成 CSV 文件

作者: SingleDiego | 来源:发表于2021-12-29 17:18 被阅读0次

    原文:How to export JavaScript array info to csv (on client side)? - Stack Overflow






    假若有一个数组如下,我们想根据该数组生成一个 CSV 文件。

    const rows = [
        ["name1", "city1", "some other info"],
        ["name2", "city2", "more info"]
    ];
    

    代码如下:

    const rows = [
        ["name1", "city1", "some other info"],
        ["name2", "city2", "more info"]
    ];
    
    let csvContent = "data:text/csv;charset=utf-8,";
    
    rows.forEach(function(rowArray) {
        let row = rowArray.join(",");
        csvContent += row + "\r\n";
    });
    

    也可以使用箭头函数来简化代码:

    const rows = [
        ["name1", "city1", "some other info"],
        ["name2", "city2", "more info"]
    ];
    
    let csvContent = "data:text/csv;charset=utf-8," 
        + rows.map(e => e.join(",")).join("\n");
    

    现在生产 CSV 文件的下载链接:

    let encodedUri = encodeURI(csvContent);
    

    我们会得到一个这样的链接:

    'data:text/csv;charset=utf-8,name1,city1,some%20other%20info%0Aname2,city2,more%20info'
    

    封装成函数,更便于使用:

    function arrayToCsv(rows) {
      let csvContent = "data:text/csv;charset=utf-8,";
    
      rows.forEach(function(rowArray) {
        let row = rowArray.join(",");
        csvContent += row + "\r\n";
      });
    
      return encodeURI(csvContent);
    }
    






    我们再扩展一下,如果数组里面是对象,我们这样转成 CSV:

    let items = [
      {name: 'tom', age: 20},
      {name: 'lily', age: 18}
    ]
    
    function objectToArray(item) {
      let content = [];
      Object.keys(item).forEach(function(key) {
        let value = item[key];
        content.push(value);
      })
    
      return content;
    }
    
    function arrayToCsv(rows) {
      let csvContent = "data:text/csv;charset=utf-8,";
    
      rows.forEach(function(rowArray) {
        let row = rowArray.join(",");
        csvContent += row + "\r\n";
      });
    
      return encodeURI(csvContent);
    }
    
    arrayToCsv(items.map(objectToArray))
    






    日常使用中,我们会发现上述方法如果导出中文信息,会导致 CSV 文件乱码,解决方法是添加 "\ufeff" 字符串。

    function arrayToCsv(rows) {
      let csvContent = "data:text/csv;charset=utf-8,\ufeff";
    
      rows.forEach(function(rowArray) {
        let row = rowArray.join(",");
        csvContent += row + "\r\n";
      });
    
      return encodeURI(csvContent);
    }
    

    相关文章

      网友评论

          本文标题:Javascript 数组生成 CSV 文件

          本文链接:https://www.haomeiwen.com/subject/lnavqrtx.html