记录下javascript生成csv文件
1、如果传入表头数据
// 生成excel,meta为表数据,data为传入数据,name为生成的文件名称
createExcel(meta, data, name) {
// '\n' 表示一行的结束,','表示数据依次放在新的单元格
let header = "";
for (let i in meta) {
header += meta[i].name + ",";
}
const table = header + "\n" +
data.map((item) => {
let result = "";
for (const key in item) {
result += item[key] + ",";
}
return result;
}).join("\n");
//encodeURIComponent解决中文乱码
let uri = "data:text/csv;charset=utf-8,\ufeff" + encodeURIComponent(table);
//通过创建a标签实现
var link = document.createElement("a");
link.href = uri;
//对下载的文件命名
link.download = name + ".csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
},
2、如果不传表头数据
// 生成excel,data为传入数据,name为生成的文件名称
createExcel(data, name) {
let tmp = [data[0]];
const header = tmp.map((item) => {
let result = "";
for (const key in item) {
result += key + ",";
}
return result;
}).join("\n");
const table = header + '\n' + data.map((item) => {
let result = "";
for (const key in item) {
if(item[key] != null) {
item[key] = item[key].toString().replace(/,/gi, ",")
}
result += item[key] + ",";
}
return result;
}).join("\n");
//encodeURIComponent解决中文乱码
let uri = "data:text/csv;charset=utf-8,\ufeff" + encodeURIComponent(table);
//通过创建a标签实现
var link = document.createElement("a");
link.href = uri;
//对下载的文件命名
link.download = name + ".csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
},