参考: https://blog.csdn.net/qq_39252501/article/details/79656317
npm install file-saver --save
npm install @type/file-saver --save-dev
npm install xlsx --save
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
exportList(){
let json = nameList;
//这个nameList (随便起的名字),是要导出的json数据
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
//这里类型如果不正确,下载出来的可能是类似xml文件的东西或者是类似二进制的东西等
this.saveAsExcelFile(excelBuffer, "nameList");
}
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 + '_' + new Date().getTime() + '.xls');
// 如果写成.xlsx,可能不能打开下载的文件,这可能与Excel版本有关
}
这样就可以啦~