在 Angular 中上传/导入 Excel 表格时,日期以数字格式显示

问题描述

我正在尝试使用 angular 实现上传 Excel 工作表,但是当工作表在浏览器中显示时,日期更改为数字格式。例如。 12-12-2020 更改为 44177.00011574074。我需要 dd-mm-yyyy 格式。请指导我在打字稿代码中需要做的更改。

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,})
}

解决方法

Excel 日期存储为浮点数。数字 1.0 表示 1900-01-01 00:00:00。其他数字表示从那天起的天数。因此,您可以使用以下内容将 Excel 日期转换为 Javascript 时间戳:const jsDate = (excelDate - 25569) * 24 * 60 * 60 * 100025569 幻数是从 1900-01-011970-01-01 的天数。 24 * 60 * 60 * 1000 是一天中的毫秒数。

但是,如果您给它正确的选择,xlsx 软件包的 util.sheet_to_json() method 可以为您做到这一点。

this.worksheetData = XLSX.utils.sheet_to_json(this.worksheetInstance,{
      raw: false,header: this.worksheetHasHeader ? 0 : 1,dateNF: "dd/mm/yyyy"
    })

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...