1、安装插件
npm installfile-saver --save
npm installxlsx --save
2、在需要使用的ts文件中引入以下代码
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
3、导出json格式数据为excel表格
exportExcel() {
// 设置表格样式,!cols为列宽
const options = {
'!cols': [
{ wpx: 100 },
{ wpx: 300 },
{ wpx: 150 },
] };
const exportData = this.getCheckedDatas(); // 此处为需要导出的内容
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(exportData);
worksheet['!cols'] = options['!cols'];
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
this.saveAsExcelFile(excelBuffer, 'bank');
}
// 将上述表格数据保存为excel并下载
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、若java提供下载接口,直接返回xml文件时,angular请求时通过blob格式接收
此处需注意:设置httpOptions时,需要设置类型为object,以免tslint报格式错误;
getExcel(): Observable<any> {
const httpOptions: object = {
responseType: 'blob',
};
return this.http.get<any>(this.bankExcelUrl, httpOptions).pipe(
tap(res => {
this.saveAsExcelFile(res,'file'); // 此处可直接保存为excel下载文件
})
);
}
网友评论