使用分页和过滤器将表格导出到 excel 文件

问题描述 投票:0回答:1

我没有在网上找到任何东西,希望这里有人能帮助我。

在我的应用程序中,我有一个包含分页和逐列过滤器的表格,问题是如果我现在去创建一个具有这些功能的 excel 文件

Excel-服务-ts

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(tableid:string, name?: string): void {
    const timeSpan = new Date().toISOString();
    const fileName = `${name}-${timeSpan}`;
    const targetTableElm = document.getElementById(tableid);
    const wb = XLSX.utils.table_to_book(targetTableElm, { sheet: name } as
 XLSX.Table2SheetOpts);
    XLSX.writeFile(wb, `${fileName}.xlsx`);
  }

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

Component.ts

createExcelFile(){
    this.excelservice.exportAsExcelFile('excel-table','Matricola' + Date.now())
  }

This is my table, in this case it will export in the excel only this 5 rows, Instead of exporting all 4397 of them (I blacked out the data)

它只导出前 5 或 10 个过滤或分页结果。

我想要的是,如果我按表中的一列进行过滤,我会得到 300 个结果,它会在 Excel 中打印 300 行,而不是 5 行,由于分页,用户实际上可以看到这些行。

angular excel typescript pagination datasource
1个回答
0
投票

而不是

XLSX.utils.table_to_book
您必须使用
XLSX.utils.json_to_sheet
并提供要导出的数据。
table_to_book
方法只会导出它显示的页面的表格数据。所以你的代码会是这样的:

public exportAsExcelFile(data: { [key: string]: any }, name?: string): void {
    const timeSpan = new Date().toISOString();
    const fileName = `${name}-${timeSpan}`;
    const wb = XLSX.utils.json_to_sheet(data);
    const excelBuffer = XLSX.write(wb, {
      bookType: "xlsx",
      type: "array",
    });
    this.saveAsExcelFile(excelBuffer, `${fileName}.xlsx`);
}

您可以向此方法提供要导出的所有数据,而不是数据。

© www.soinside.com 2019 - 2024. All rights reserved.