How to maintain the text format (No Formatting) when export to excel using XLSX Angular

3.6k views Asked by At

I have the simplified working code below:

It is trying to simulate and generate 3 rows of data to HTML using tag. I have it "reference" using #myTable. The Data is being passed and an excel file is being generated (thankfully).

However, the data is formatted by excel (i think on its own during write).

Can anyone guide me on how to not make XLSX not format and export data to Excel as in tag?

HTML

<table #myTable class="table table-striped table-condensed text-nowrap">
  <thead>
    <tr>
      <th></th>
      <th>Col1</th>
      <th>Col2</th>
      <th>Col3</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let number of ['31.03.2020','10.10.2019','0013268']" class="form-group">
      <td></td>
      <td name="col1">{{ number }}</td>
      <td name="col2">{{ number }}</td>
      <td name="col3">{{ number }}</td>
    </tr>
  </tbody>
</table>

<button id="table-export-message" [tableElement]="myTable"
  class="btn btn-default btn-primary float-right tableexport-string target" style="margin-right:10px">
  <span class="fa fa-file-excel-o"></span>
  Export Excel
</button>

Component

private exportToTable() {
  const ws: XLSX.WorkSheet = XLSX.utils.table_to_sheet(this.tableElement);
  const wb: XLSX.WorkBook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

  /* save to file */
  XLSX.writeFile(wb, 'SheetJS.xlsx');
}

The result on EXCEL below. As you can see, only '31.03.2020' is displayed correctly. However,

  1. '10.10.2019' is displayed as "10/10/2019" (Expected : 10.10.2019)
  2. '0012345' is displayed as "12345" (Expected: 0012345)

enter image description here

Thank you for your time!

Update with solution 1: Good idea but not the correct solution as The excel also have ' (apostrophe). enter image description here

Also the table displays the apostrophe. enter image description here

1

There are 1 answers

0
AHK On

I have found how to add the table without any formatting. After taking more time to understand the (abit confusing) README for Angular XLSX, There is a more parameters which will be accepted and one of it being

raw : boolean

So the updated code line would be:

const ws: XLSX.WorkSheet=XLSX.utils.table_to_sheet(this.tableElement,  {raw:true});