在 Angular 中使用 xlsx - 如何使 excel 自动将日期识别为列中的实际日期?

Using xlsx in Angular - How to make excel identify the dates as actual dates in column automatically?

我有一个创建 excel 个文件的 angular 服务:

import { Injectable } from '@angular/core';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';

const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';

@Injectable()
export class ExcelService {

  constructor() { }

  public exportAsExcelFile(json: any[], excelFileName: string): void {
    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
    console.log('worksheet',worksheet);
    const wb: XLSX.WorkBook = { Sheets: { data: worksheet }, SheetNames: ['data'] };
    if(!wb.Workbook) wb.Workbook = {};
    if(!wb.Workbook.Views) wb.Workbook.Views = [];
    if(!wb.Workbook.Views[0]) wb.Workbook.Views[0] = {};
    wb.Workbook.Views[0].RTL = true;
    const excelBuffer: any = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    this.saveAsExcelFile(excelBuffer, excelFileName);
  }

  private saveAsExcelFile(buffer: any, fileName: string): void {
    const data: Blob = new Blob([buffer], {
      type: EXCEL_TYPE
    });
    FileSaver.saveAs(data, fileName + '_export_' + new Date().getTime() + EXCEL_EXTENSION);
  }

}

该服务有效,它创建的文件的日期格式格式正确,但Excel只能识别它们如果我一个一个地触摸它们或编辑整个列的设置。

我就是这样激活服务的:

const temp = this.dataSource.data.map(e => {
  return {
    'id': controlValueIfNull(e.Id),
    'date': '30/06/2020',
    'time': seperateDateFromHour(e.DonationHour, 'GET_HOUR_ONLY'),
  }
});
this.excelService.exportAsExcelFile(temp,"Donations");

日期的格式如下:'01/12/2020' - 如果我只取 excel 文件并记录下来,但是当我导出它时,它不会自动识别它们。

有什么想法吗?我很想得到一些帮助:)

终于解决了! 无需格式化日期(它适合我的国家/地区格式)。 我没有像 '17/02/2020' 那样调整和发送字符串,而是把它放在:

'column name': new Date(dateChosen)

刚刚好! 现在存在 Excel 按日期过滤。