angular中分页的table导出到Excel文件

曹奇文
2023-12-01

1、安装file-saver、@types/file-saver和xlsx

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、在component文件中加入如下代码

import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';

......

exportTable() {
    const exportItem = this.item; //this.item是一个数组,包含需要导出的内容
  
    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 + '_' + moment().format('YYYYMMDDHHmmss') + '.xlsx');
}
 类似资料: