angular6 将表格的JSON数据导出为excel
前言:
项目中遇到一个将表格数据输出为excel文件的需求,本需求只是简单地将简单表格的数据输出到excel,并没有涉及表格样式的复杂处理。
1、安装依赖环境
npm install file-saver --save
npm install @types/file-saver --save-dev
npm install xlsx --save
2、html 导出按钮
<button type="button" class="btn btn-sm btn-success" (click)="exportTable()">导出</button>
3、TS 文件
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、输出结果