JavaScript实现数据导出到Excel表格功能指南
JavaScript实现数据导出到Excel表格功能指南。
一 相关资料
https://zhuanlan.zhihu.com/p/470312515
https://github.com/rockboom/SheetJS-docs-zh-CN/
npm install xlsx -save
二 代码示例
2.1 excelOpt.ts
declare var XLSX: any;
/**
* header: 标题 ['name', 'id']
* body: 数据 [['zhao', 2],['ma', 3]]
* name: 文件名 '数据导出'
*/
export function expoerExcel(header = [], body = [], name = '') {
let dataSource:any = [];
dataSource.push(header);
dataSource = [...dataSource, ...body];
const worksheet = XLSX.utils.aoa_to_sheet(dataSource);
const new_workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(new_workbook, worksheet, 'sheet1');
XLSX.writeFile(new_workbook, `${name || '导出报表'}.xlsx`);
}
2.2 index.html
<script src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/xlsx/0.18.2/xlsx.full.min.js"></script>