我实现了一种将文档下载到 Angular 中的 Excel 电子表格的方法,如下所示。有人可以让我知道如何为以下 void
方法实现承诺。
ExportService
类:
export class ExportService {
constructor() { }
fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
fileExtension = '.xlsx';
public exportExcel(jsonData: any[][], fileName: string): void {
const x: XLSX.WorkSheet = XLSX.utils.json_to_sheet(jsonData[0]);
const z: XLSX.WorkSheet = XLSX.utils.json_to_sheet(jsonData[1]);
const b: XLSX.WorkBook = {
Sheets: {
'product': x,
'sales': z
},
SheetNames: ['product', 'sales']
};
const excelBuffer: any = XLSX.write(b, { bookType: 'xlsx', type: 'array' });
this.saveExcelFile(excelBuffer, fileName);
}
private saveExcelFile(buffer: any, fileName: string): void {
const data: Blob = new Blob([buffer], { type: this.fileType });
FileSaver.saveAs(data, fileName + this.fileExtension);
}
}
组件中的导出方法如下。
export() {
this.callProgress = true;
this.progressText = "";
this.salesProductForABC().then(() => {
let products: Array<Array<any>> = [];
products.push(this.productContent, this.salesProductContent);
let month = new Date().getUTCMonth() + 1;
let day = new Date().getUTCDate();
let year = new Date().getUTCFullYear();
let fileName = `${month}${day}${year}`;
this.exportService.exportExcel(products, fileName)
this.callProgress = false;
})
}
``
`
答案 0 :(得分:1)
改变
this.saveExcelFile(excelBuffer, fileName);
到
return this.saveExcelFile(excelBuffer, fileName);
和
FileSaver.saveAs(data, fileName + this.fileExtension);
到
return FileSaver.saveAs(data, fileName + this.fileExtension);
当然,您需要将 void
更改为返回类型。
exportExcel
和 saveExcelToFile
异步以便能够等待它们例如
public exportExcel(jsonData: any[][], fileName: string): void {
到
public async exportExcel(jsonData: any[][], fileName: string): Promise<void> {
改变
this.exportService.exportExcel(products, fileName)
this.callProgress = false;
到
this.exportService.exportExcel(products, fileName).catch(e =>
alert(e.message)).finally(() => this.callProgress = false;)
salesProductForABC
添加错误处理并添加正确的 catch
。在 Promise 中缺少错误提示是非常糟糕的做法,并且会给用户带来令人沮丧的错误。请记住 - 在您的代码/基础设施/程序输入中,一切都可能被破坏。不要离开很重要:
最后,您的代码不包含 FileSaver
,但您可能还应该返回 promise,并且还应该处理接收。