如何在导出 MatTable 组件时在文件名中添加时间戳?

How to add timestamp in filename while exporting MatTable components?

我正在使用 mat-table-exporter npm 模块导出 mat table 组件。

我可以使用 test 作为导出文件的名称正确导出它。

<button mat-raised-button (click)="exporter.exportTable('csv', {fileName:'test',
   Props: {Author: 'myName'}})">
   Export
</button>

我还想在我正在修改的导出文件的名称中添加时间戳fileName test-{new Date()} 如下:

<button mat-raised-button (click)="exporter.exportTable('csv', {fileName:'test-{new Date()}',
   Props: {Author: 'myName'}})">
   Export
</button>

以上代码抛出编译时错误。

这个导出函数不能在组件的 .ts 文件中有什么具体原因吗?这样调试起来就容易多了,而且它提供了更好的配置选项。

exportTable(): void {
  this.exporter.exportTable('csv', {
    filename: `test-${new Date().toISOString()}`,
    Props: { 
      Author: 'myName'
    }
  })
}

然后在模板中直接调用即可。

<button mat-raised-button (click)="exportTable()">Export</button>

我是这样解决的;在文件 .ts 中放这个

import { formatDate} from '@angular/common';
@Component({
    // ...
})
export class AppComponent  {
datenow = new Date();
formatted: string;
constructor() {
      this.nowFormatted = formatDate(this.datenow, 'dd-MM-yyyy', 'en-US');
   }
}

并在 HTML 放这个

                    <button style="float: right;"  (click)="exporter.exportTable('xlsx', {fileName:'Applications_'+formatted})">
                    <img src="../../../assets/iconos/excel.png" alt="" />
                    </button>

ts 中的格式化变量现在使用当前日期格式化。

希望对您有所帮助