【问题标题】:How Angular Export to Excel with formatting cell?如何使用格式化单元格 Angular 导出到 Excel?
【发布时间】:2019-07-01 14:48:38
【问题描述】:

使用 exportAsExcelFile 方法的我的 Excel 服务:

    public exportAsExcelFile(json: any[], excelFileName: string): void {
    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: 'xls', type: 'array' });
    this.saveAsExcelFile(excelBuffer, excelFileName);
  }

  private saveAsExcelFile(buffer: any, fileName: string): void {
    const data: Blob = new Blob([buffer], {type: EXCEL_TYPE});
    FileSaver.saveAs(data, fileName + '_' + new  Date().getTime() + EXCEL_EXTENSION);
  }

我的组件与方法 exportDataToExcel() :

dataToExport: any = [];
exportFileName: string = "TRANSACTION_HISTORY_REPORT";


exportDatatoExcel(){

    this.myAPIService.getData().then(
      (data) => {

        data.forEach((data, index) => {

            this.dataToExport.push({
              no: index + 1,
              total_item_sold: data.detailItem.length,
              total_price: data.totalPrice,

            });
          });

        if(this.dataToExport.length > 0){
          if(this.exportFileName == "") this.exportFileName = "default";
          this.excelService.exportAsExcelFile(this.dataToExport, 
          this.exportFileName);
        }
      }
    );

  }

如何在 Excel 中通过格式化会计单元格导出该 json total_price?

【问题讨论】:

    标签: angular export-to-excel


    【解决方案1】:

    您使用的实用程序不支持开箱即用的单元格格式。您需要自己在 sheetjs 中更深入地处理它。

    您可以迭代单元格并相应地更改 cell.z 属性,因为它代表单元格格式。

    /* new format */
    var fmt = "0.00";
    /* change cell format of range B2:D4 */
    var range = { s: {r:1, c:1}, e: {r:2, c:3} };
    for(var R = range.s.r; R <= range.e.r; ++R) {
      for(var C = range.s.c; C <= range.e.c; ++C) {
        var cell = ws[XLSX.utils.encode_cell({r:R,c:C})];
        if(!cell || cell.t != 'n') continue; // only format numeric cells
        cell.z = fmt;
      }
    }
    

    这是一个小提琴的例子: https://jsfiddle.net/1ny97xrb/1/

    (https://github.com/SheetJS/js-xlsx/issues/966)

    【讨论】:

      猜你喜欢
      • 2016-04-23
      • 1970-01-01
      • 2017-02-22
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多