解决方案:使用 excelStyles 强制文本格式

1、在 ag-gridExcel 样式表中,定义一个 文本格式样式

gridOptions = {
  columnDefs: this.columnDefs,
  excelStyles: [
    {
      id: 'textFormat',        // 对应上面的 cellClass
      dataType: 'string'       // Excel 中会以文本格式导出
    }
  ]
};

2、在对应的columnDefs 数组中,设置及cellClass数组包含'textFormat',这样就会设置这列在导出的时候,是字符串类型。

columnDefs = [
  { headerName: 'Number', field: 'number', cellClass: 'textFormat' },
  { headerName: 'Name', field: 'name' }
];

// 在导出时配置样式
onBtExport() {
  const params = {
    fileName: 'export.xlsx',
    allColumns: true,
    processCellCallback: (params) => {
      // 保证所有单元格值是字符串
      return params.value != null ? String(params.value) : '';
    }
  };

  this.gridOptions.api.exportDataAsExcel(params);
}

核心点

  1. cellClass + excelStyles

    • 在 columnDefs 里给每一列加 cellClass: 'textFormat'
    • 在 excelStyles 里定义 dataType: 'string'
    • Excel 导出时会把单元格类型强制为文本。
  2. processCellCallback

    • 虽然 Excel 样式已经强制为文本,processCellCallback 可以确保值被转换为字符串,避免 null 或 undefined 出现问题。
  3. 避免科学计数法

    • 关键是 dataType: 'string',Excel 不会把长数字自动转为科学计数法。
    • 0 开头的数字也会被保留。

PS: 上面方法,亲测有效,而且在ag-grid-angular 22.1.1 等老版本,中也是有效的,可以比较好的使用

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐