- 导出表格
- { name, header, data }
- name 表格名称,非必须
- header 表头数据,必须,{ name[必须], key[必须], callback[非必须] }, callback(item) 回调函数中,item包含原始数据已经数据的序号, item = {raw, _index}
- data 表格数据,非必须
工具源码
function extractHeader(header) {
const title = [];
const key = [];
const callback = [];
for (let i = 0; i < header.length; i++) {
const item = header[i];
if (item.name) title.push(item.name);
if (item.key) key.push(item.key);
if (item.key && item.callback) callback[item.key] = item.callback;
}
return { title, key, callback };
}
function error(value) {
console.log(value);
return false;
}
function getName(name) {
if (name) {
return name + ".csv";
} else {
return new Date().toISOString().substring(0, 10) + ".csv";
}
}
function handeData(raw, csvHead) {
const csvData = [];
for (let i = 0; i < raw.length; i++) {
const cache = [];
for (let j = 0; j < csvHead.key.length; j++) {
const key = csvHead.key[j];
if (csvHead.callback[key])
cache.push(csvHead.callback[key]({ raw: raw[i], _index: i }));
else cache.push(raw[i][key] ?? "");
}
csvData.push(cache.join(",") + "\n");
}
return csvData;
}
function downFile(csvName, csvData) {
const csvURL =
"data:text/csv;charset=utf-8,\ufeff" + encodeURIComponent(csvData.join(""));
let downloadLink = document.createElement("a");
downloadLink.href = csvURL;
downloadLink.download = csvName;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
const exportCsv = function(params = {}) {
if (!params["header"]) return error(`[EEROR]:没有传入表头!`);
const csvData = [];
const csvName = getName(params["name"]);
const csvHead = extractHeader(params["header"]);
csvData.push(csvHead.title.join(",") + "\n");
csvData.push(...handeData(params["data"], csvHead));
downFile(csvName, csvData);
};
export default exportCsv;
使用例子
exportCsv({
name: "",
header: [{
name: "序号",
key: "index",
callback: item => {
return item._index;
}
}],
data: []
}};