由于您必须在角度应用程序中显示数据,因此最好的解决方案是将数据作为 json 发送并使用以下 npm 包:https://www.npmjs.com/package/xlsx https://www.npmjs.com/package/xlsx将 json 转换为 xlsx 文件或 csv
这是我为此编写的示例服务,只需创建此服务并在需要时调用该函数:
excel.service.ts
import { Injectable } from '@angular/core';
import * as XLSX from 'xlsx';
@Injectable({
providedIn: 'root'
})
export class ExcelService {
constructor() { }
jsonToExcelSheet(data: any[], file_name = 'temp.xlsx') {
const workBook = XLSX.utils.book_new(); // create a new blank book
const workSheet = XLSX.utils.json_to_sheet(data);
let wscols = [{ wpx: 150 }, { wpx: 200 }, { wpx: 150 }, { wpx: 150 }];
workSheet['!cols'] = wscols; // set cell width
XLSX.utils.book_append_sheet(workBook, workSheet, 'data'); // add the worksheet to the book
return XLSX.writeFile(workBook, file_name); // initiate a file download in browser
}
jsonToCSV(data: any[], file_name = 'temp') {
const workBook = XLSX.utils.book_new(); // create a new blank book
const workSheet = XLSX.utils.json_to_sheet(data);
XLSX.utils.book_append_sheet(workBook, workSheet, 'data'); // add the worksheet to the book
return XLSX.writeFile(workBook, `${file_name}.csv`); // initiate a file download in browser
}
}
现在,如果您想使用此服务,只需将其导入所需的位置即可组件.ts
import { ExcelService } from 'src/services/excel.service';
constructor(private _excelService: ExcelService){}
async downloadWorksheet() {
let downloadData = {} // load your data here
// export the json as excelsheet
await this._excelService.jsonToExcelSheet(downloadData);
}