【问题标题】:How to add timestamp in filename while exporting MatTable components?导出 MatTable 组件时如何在文件名中添加时间戳?
【发布时间】:2026-02-13 00:45:01
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

    标签: html angular npm angular-material interpolation


    【解决方案1】:

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

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

    然后在模板中调用它。

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

    【讨论】:

    • 这会引发错误TS2552: Cannot find name 'exporter'.
    • 那不是问题吗?我不知道exporter 是如何提供的,在我的代码中this.exporter 只是一个猜测。
    【解决方案2】:

    我以这种形式解决了;在文件 .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 中的格式化变量现在用 currentDate 格式化。

    希望对你有所帮助

    【讨论】: