csv是一种文本格式,有两个规则:

1. 一行就是一行以\n分割。
2. 一行之内以','分割

1. node中处理不含汉字的字符串

var fs = require('fs');
const aaa = "name,age\nallen,29";
fs.writeFile('file.csv', aaa, function(err) {
  if (err) throw err;
  console.log('file saved');
});

保存的结果:

clipboard.png

2. node中处理包含汉字的字符串

var fs = require('fs');
const aaa = "name,age,家乡\nallen,29,河南";
fs.writeFile('file.csv', "\ufeff"+aaa, function(err) {
  if (err) throw err;
  console.log('file saved');
});

结果:

clipboard.png

3. 页面中处理非汉字

<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="author" content="oscar999">
  <title>
  </title>
  <script>
    function clickDownload(aLink)
    {
         var str = "col1,col2,col3\nvalue1,value2,value3";
         str =  encodeURIComponent(str);
         aLink.href = "data:text/csv;charset=utf-8,"+str;
         aLink.click();
    }
  </script> 
  </head>
  <body>
    <a id="test" onclick="clickDownload(this)" download="downlaod.csv" href="#">download</a>
  </body>
</html>

4. 页面中处理汉字

<head>
  <meta http-equiv="content-type" content="text/html; charset=gb2312">
  <meta name="author" content="oscar999">
  <title>
  </title>
  <script>
    function clickDownload(aLink)
    {
         var str = "栏位1,栏位2,栏位3\n值1,值2,值3";
         str =  encodeURIComponent(str);
         aLink.href = "data:text/csv;charset=utf-8,\ufeff"+str;
         aLink.click();
    }
  </script> 
  </head>
  <body>
    <a id="test" onclick="clickDownload(this)" download="downlaod.csv" href="#">download</a>    
  </body>
</html>

5. 参考文章

Web 端 js 导出csv文件(使用a标签)
json2csv


唯见长江天际流
827 声望11 粉丝

黄鹤楼送孟浩然之广陵


« 上一篇
prototype