【exportExcel】单纯靠js不用任何其他第三方插件导出xls格式文件
方法/** * 纯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 border1; tableHtml theadtr; headers.forEach((h) { tableHtml th${h.title}/th; }); tableHtml /tr/theadtbody; // 2.拼接行数据 tableData.forEach((row) { tableHtml tr; headers.forEach((h) { let val row[h.key] || ; // mso-number-format:\ 强制文本避免长数字科学计数 tableHtml td stylemso-number-format:\\${val}/td; }); tableHtml /tr; }); tableHtml /tbody/table; // 封装成完整xls兼容html文档th增加背景色其余原有逻辑完全不变 const htmlContent html xmlns:ourn:schemas-microsoft-com:office:office xmlns:xurn:schemas-microsoft-com:office:excel xmlnshttp://www.w3.org/TR/REC-html40 head meta charsetUTF-8 meta http-equivContent-Type contenttext/html;charsetutf-8/ style table { font-family: Microsoft YaHei,微软雅黑; font-size: 14px; text-align: left; } th,td { text-align: left; } /* 解决br标签在单元格里面会被拆分多行 */ br {mso-data-placement:same-cell;} /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;//⚠️只能 .xls不能强行改xlsx 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)}, }); },