简体   繁体   English

在 ag-grid 上使用正确的单元格格式导出到 excel

[英]Exporting to excel with proper cell formatting on ag-grid

When I export a table to excel using ag-grid's own exportDataAsExcel() the resulting excel contains dates as General data type instead of Date .当我使用 ag-grid 自己的exportDataAsExcel()将表导出到 excel 时,生成的 excel 包含日期作为General数据类型而不是Date

[ [excel图片 ] ]

I have used this:我用过这个:

exportDataAsExcel({
   processCellCallback: ({col, val}) => {( /*date value formatting here*/ )}
})

to format both Date , string with proper date formatting (DD/MM/YYYY) but I can't make excel properly recognize these cells as Date instead of General用正确的日期格式(DD/MM/YYYY)格式化Datestring ,但我无法让 excel 正确地将这些单元格识别为Date而不是General

This is reproducible with the excel export examples on their website: https://www.ag-grid.com/javascript-grid-excel/?framework=all#gsc.tab=0这可以通过其网站上的 excel 导出示例重现: https : //www.ag-grid.com/javascript-grid-excel/?framework=all#gsc.tab=0

I've used this code to apply value formatter in excell as well:我也使用此代码在 Excel 中应用值格式化程序:

this.gridOptions.api.exportDataAsExcel({
  processCellCallback: (params) => {
    const colDef = params.column.getColDef()
    // try to reuse valueFormatter from the colDef
    if (colDef.valueFormatter) {
      const valueFormatterParams: ValueFormatterParams = {
        ...params,
        data: params.node.data,
        node: params.node!,
        colDef: params.column.getColDef()
      };
      return colDef.valueFormatter(valueFormatterParams);
    }
    return params.value;
  },
});

You need to do three things:你需要做三件事:

  1. When instantiating the Ag-Grid, you need to add (thanks to another user's answer elsewhere )实例化 Ag-Grid 时,需要添加(感谢其他用户在别处的回答

     let excelStyles = [ { id: "ExcelDateTime", dataType: "dateTime", numberFormat: { format: "yyyy-mm-dd hh:mm:ss;;;" } }, { id: "ExcelDate", dataType: "dateTime", numberFormat: { format: "yyyy-mm-dd;;;" } } ]; ... <AgGridReact ... //such as rowData={rowData} excelStyles={excelStyles} ... />;
  2. For columns that are dates:对于日期列:

     colDef.cellClass = "ExcelDateTime";

    or

     colDef.cellClass = "ExcelDate";

    as appropriate, and视情况而定,以及

  3. in your processCellCallback , format the date as an ISO date: "yyyy-mm-ddTHH:MM:ss"在您的processCellCallback ,将日期格式化为 ISO 日期: "yyyy-mm-ddTHH:MM:ss"

Assuming that you are in control of the server-side application, I have found it easier to do the export from the server-side for any non-trivial exports / formatting.假设您控制着服务器端应用程序,我发现从服务器端导出任何非平凡的导出/格式都更容易。

By doing it on the server, you are in complete control of the data and the production of the Excel file, and not dependent on the limits of Ag-Grid's implementation.通过在服务器上执行此操作,您可以完全控制数据和 Excel 文件的生成,而不受 Ag-Grid 实施的限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM