Issue
I am trying to implement uploading the excel sheet using angular but when the sheet is displayed in browser date is changed to number format. For ex. 12-12-2020 is changed to 44177.00011574074. I need it in dd-mm-yyyy format. Please guide me the changes I need to do in my typescript code.
app.component.html
<button button mat-raised-button class="btn-primary" color="primary" style="margin: 1%;"
(click)="triggerFileSelector($event)" style="margin: 1%;">
Choose File
</button>
<!-- Code to display table -->
<section class="section">
<table class="material-table">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tr *ngFor="let rowData of tableData">
<td value="Delete" (click)="deleteRow(rowData)">X</td>
<td *ngFor="let schema of tableSchema"
[ngStyle]="{'background-color': (rowData[schema.field].value) ? 'white' : '#ff9999' }">
<span #el contenteditable (blur)="rowData[schema.field].value = el.innerText">
{{ rowData[schema.field].value }}
</span>
</td>
</tr>
</table>
</section>
app.component.ts
triggerFileSelector(e: any): void {
e.preventDefault()
this.fileInput.nativeElement.click()
}
handleFileInput(files: FileList): void {
this.workbookFile = files.item(0)
this.workbookFileName = this.workbookFile.name
this.readFile()
}
readFile(): void {
const temporaryFileReader = new FileReader()
temporaryFileReader.onerror = () => {
temporaryFileReader.abort()
return new DOMException('Problem parsing input file.')
}
temporaryFileReader.onload = (e: any) => {
/* read workbook */
const bstr: string = e.target.result
this.workbookInstance = XLSX.read(bstr, { type: 'binary' })
/* grab first sheet */
this.worksheetName = this.workbookInstance.SheetNames[0]
this.readSheet(this.worksheetName)
}
temporaryFileReader.readAsBinaryString(this.workbookFile)
}
readSheet(sheetName: string) {
this.worksheetInstance = this.workbookInstance.Sheets[sheetName]
this.worksheetData = XLSX.utils.sheet_to_json(this.worksheetInstance, {
header: this.worksheetHasHeader ? 0 : 1,
})
}
Solution
Excel dates are stored as floating-point numbers. The number 1.0 means 1900-01-01 00:00:00
. And other numbers mean days since that day. So, you can convert an Excel date to a Javascript timestamp with something like this: const jsDate = (excelDate - 25569) * 24 * 60 * 60 * 1000
. The 25569
magic number is the number of days from 1900-01-01
to 1970-01-01
. 24 * 60 * 60 * 1000
is the number of milliseconds in a day.
But the xlsx package’s util.sheet_to_json()
method does this for you if you give it the right options.
this.worksheetData = XLSX.utils.sheet_to_json(this.worksheetInstance, {
raw: false,
header: this.worksheetHasHeader ? 0 : 1,
dateNF: "dd/mm/yyyy"
})