方法
/**
* 纯JS无第三方库 导出HTML版xls
* @param {Array} tableData 数组数据源
* @param {Array} headers [{title:'表头名称', key:'字段key'}]
* @param {String} fileName 文件名不带后缀
*/
exportExcel(_this, { tableData, headers, fileName = `导出文件` }) {
headers ||
(headers = _this.data_sgs.defaultColumns.map((v) => ({
key: v.value,
title: v.label,
})));
// 1.拼接表头
let tableHtml = '<table border="1">';
tableHtml += "<thead><tr>";
headers.forEach((h) => {
tableHtml += `<th>${h.title}</th>`;
});
tableHtml += "</tr></thead><tbody>";
// 2.拼接行数据
tableData.forEach((row) => {
tableHtml += "<tr>";
headers.forEach((h) => {
let val = row[h.key] || "";
// mso-number-format:\@ 强制文本,避免长数字科学计数
tableHtml += `<td style="mso-number-format:'\\@'">${val}</td>`;
});
tableHtml += "</tr>";
});
tableHtml += "</tbody></table>";
// 封装成完整xls兼容html文档,th增加背景色,其余原有逻辑完全不变
const htmlContent = `
<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<style>
table {
font-family: "Microsoft YaHei",微软雅黑;
font-size: 14px;
text-align: left;
}
th {
font-family: "Microsoft YaHei",微软雅黑;
font-size: 14px;
text-align: left;
vertical-align: middle;
}
td {
font-family: "Microsoft YaHei",微软雅黑;
font-size: 14px;
text-align: left;
vertical-align: middle;
}
</style>
</head>
<body>
${tableHtml}
</body>
</html>`;
// 生成blob并下载
const blob = new Blob([htmlContent], {
type: "application/vnd.ms-excel",
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `${fileName}.xls`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
},
demo
// 导出Excel表格
exportExcel(d) {
let selection = this.$refs.table.selection;
this.$g.exportExcel(this, {
tableData: selection.length ? selection : this.tableData_bk,
fileName: `导出${this.$g.date.get_yyyyMMddHHmmss(`now`)}`,
});
},