// 输出base64编码
const base64 = s => window.btoa(unescape(encodeURIComponent(s)));
function checkNullOrUndefined(value) {
return (!value && value != 0) || (typeof(value) == "undefined")
}
export function exportJsonToExcel({ header = [], headerLabel = "", headerProp = "", jsonData = [], worksheet = 'Sheet', filename = "table-list" } = {}) {
// 列标题
let str = '
';
for (let i = 0; i < header.length; i++) {
str += `${header[i][headerLabel]} | `
}
str += "
"
// 循环遍历,每行加入tr标签,每个单元格加td标签
for (let i = 0; i < jsonData.length; i++) {
str += '';
for (const obj of header) {
// 增加\t为了不让表格显示科学计数法或者其他格式
str += `${ checkNullOrUndefined(jsonData[i][obj[headerProp]]) ? "" : jsonData[i][obj[headerProp]] + '\t'} | `;
}
str += '
';
}
// Worksheet名
const uri = 'data:application/vnd.ms-excel;base64,';
// 下载的表格模板数据
const template = `
`;
// 下载模板
// window.location.href = uri + base64(template);
// 通过创建a标签实现
const body = document.getElementsByTagName("body")[0];
const link = document.createElement("a");
body.appendChild(link);
link.href = uri + base64(template);
link.download = `${filename}.xls`;
link.click();
document.body.removeChild(link);
// link.parentNode.removeChild(link);
}