JS原生导出CSV文件

什么时候需要用到此功能

当项目需要导出简易表格文件,又不希望引入臃肿的表格导出组件时,可以使用JS原生导出CSV类表格文件,也可以使用excel和wps打开

直接上代码

通过二维数组导出数据​

export_csv: function(list, name) {
  const newList = list.map(res => res.join(','))
  const data = newList.join(',\n')
  // “\ufeff” BOM头
  var uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(data);
  var downloadLink = document.createElement("a");
  downloadLink.href = uri;
  downloadLink.download = (name+".csv")||"temp.csv";
  document.body.appendChild(downloadLink);
  downloadLink.click();
  document.body.removeChild(downloadLink);
},


export_csv([['123', '456', '789'], ['987', '654', '321']],  'test')

通过字符串导出数据​

export_csv: function(data, name) {
  // “\ufeff” BOM头
  var uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(data);
  var downloadLink = document.createElement("a");
  downloadLink.href = uri;
  downloadLink.download = (name+".csv")||"temp.csv";
  document.body.appendChild(downloadLink);
  downloadLink.click();
  document.body.removeChild(downloadLink);
},


export_csv('123,456,789,\n987,654,321',  'test')

效果如下,文件名为test.csv

通过dom table导出数据

export_table: function(selector, name) {
  var self = this;
  if (document.querySelectorAll(selector).length == 0) {
    alert('Selector "'+selector+'" not exists!');
    return false;
  }
  self.export_csv(self.get_table_data(selector), name);
},

export_table('.excel', '收支明细_')

导出class为.excel的表格数据​

获取dom table表格数据

get_table_data: function(selector) {
  var data = "";
  document.querySelectorAll(selector+' tr').forEach(function(t) {
    var tmp = [];
    t.querySelectorAll('th,td').forEach(function(e){
      tmp.push(e.innerText.replace("\n", "")); // 单元格里含有多个html元素可能会获取到换    行符
    });
    data += tmp.join(",") + "\n";
  });
  return data;
}

get_table_data('.excel')
复制

获取class为.excel的表格数据​

csv
81 views
Comments
登录后评论
Sign In