其他分享
首页 > 其他分享> > angular6 导出Excel文件

angular6 导出Excel文件

作者:互联网

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 left-small-interval" (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');
}

.......

 

标签:XLSX,const,xlsx,Excel,saver,导出,angular6,file,data
来源: https://www.cnblogs.com/lucky-heng/p/11013335.html