前言
项目中遇到一个将表格数据输出为excel文件的需求,本需求只是简单地将简单表格的数据输出到excel,并没有涉及表格样式的复杂处理。
1、安装依赖环境
1 2 3 |
npm install file-saver --save npm install @types/file-saver --save-dev npm install xlsx --save |
2、html 导出按钮
1 |
<button type="button" class="btn btn-sm btn-success" (click)="exportTable()">导出</button> |
3、TS 文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import * as FileSaver from 'file-saver'; import * as XLSX from 'xlsx'; ...... jsonData: any = [ { "姓名": "张三", "工號": "22", "英文名": "zhangsan", "部门": "技术部", "性别": "男", "手机": "15177641999", "个人邮箱": "610336688@qq.com" }, { "姓名": "李四", "工號": "33", "英文名": "李四", "部门": "人事部", "性别": "女", "手机": "15177641988", "个人邮箱": "978336688@qq.com" }]; exportTable() { const exportItem = this.jsonData; const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(exportItem); const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] }; const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' }); this.saveAsExcelFile(excelBuffer, 'report'); } private saveAsExcelFile(buffer: any, fileName: string) { const data: Blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' }); FileSaver.saveAs(data, fileName + '.xlsx'); } |
4、输出结果
即可。
本文来自倒带_with ,本文观点不代表蓝洛水深立场,转载请联系原作者。