只是记录一下 没啥好说的! 直接上代码吧!
var csvApp = {
exportCsv: function(data, name) {
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);
},
exportTable: function(selector, name) {
if (document.querySelectorAll(selector).length == 0) {
alert('Selector "'+selector+'" not exists!');
return false;
}
this.exportCsv(this.tableData(selector), name);
},
tableData: function(selector) {
var data = "";
var tmp = [];
document.querySelectorAll(selector+' tr').forEach(function(t) {
tmp = [];
t.querySelectorAll('th,td').forEach(function(e){
tmp.push(e.innerText.replace("\n", ""));
});
data += tmp.join(",") + "\n";
});
return data;
}
};
// 直接导出数据
csvApp.exportCsv("wgc,123456,456789,126345","test");
// 导出表格
csvApp.exportTable("#table_id", "test_1");
// 脚本生成
var tmp = [];
var data = "姓名,性别,电话\n";
for(var i=0;i<10000;i++){
tmp = [];
tmp.push('我是'+i+"号");
tmp.push("男");
tmp.push('182252'+i);
data += tmp.join(",") + "\n";
}
csvApp.exportCsv(data,'test');