2

This is my mock data

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 Results:

Actual Output

Expected Results:

Expected Output

I'm trying to tweak the logic to handle the array of objects and specify the position in the xl, Can I achieve the above expected results based on the mockData with xlsx library ??

1 Answer 1

2

I solved this by changing

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

to:

@ViewChild('reportTable') reportTable: ElementRef;

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

Now I'm exporting HTML Table to Excel and I see the expected results now

Sign up to request clarification or add additional context in comments.

1 Comment

I just want to thanks you a lot, your code works really well for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.