Angular XLSX库,导出对象数组

时间:2019-10-31 16:28:42

标签: angular typescript xlsx

这是我的模拟数据

mockData: any[] = [
  {
    "id": "456",
    "requestType": "Test",
    "requestDate": "10/15/20",
    "status": "Fail",
    "product": [
       {
         "productName": "product 1",
         "productQty": "12"
       },
       {
         "productName": "product 2",
         "productQty": "22"
       }
    ]
  }
]

.ts:

toExportFileName(excelFileName: string): string {
    var date = new Date();
    return `${excelFileName}_${date.getMonth() + 1}${date.getDate()}${date.getFullYear()}.xlsx`;
  }

  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'] };
    XLSX.writeFile(workbook, this.toExportFileName(excelFileName));
  }

  exportToExcel() {
    this.exportAsExcelFile(this.mockData, 'Shado_Test_Report');
  }

实际结果:

Actual Output

预期结果:

Expected Output

我正在尝试调整逻辑以处理对象数组并指定xl中的位置,我能否基于带有xlsx库的mockData实现以上预期的结果?

1 个答案:

答案 0 :(得分:1)

我通过更改来解决了

const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);

收件人:

@ViewChild('reportTable') reportTable: ElementRef;

const ws: XLSX.WorkSheet=XLSX.utils.table_to_sheet(this.reportTable.nativeElement);

现在我将HTML表导出到Excel,现在可以看到预期的结果