You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Ant Design列顺序重构数据适配react-export-table-to-excel导出

解决react-export-table-to-excel导出数据与列标题不匹配的问题

当使用react-export-table-to-excel导出分页表格的全部数据时,因无法通过ref获取完整表格,只能采用插件的纯数据导出方案。但如果原始数据对象的属性顺序与Ant Design的columns配置顺序不一致,就会出现导出的Excel中数据字段和对应标题错位的问题。

要解决这个问题,只需编写一个转换函数,将原始数据重构为属性顺序完全匹配columns配置顺序的新数组即可:

// 数据转换函数:让数据属性顺序与columns的dataIndex顺序一致
const transformDataForExport = (rawData, columns) => {
  return rawData.map(item => {
    const newItem = {};
    columns.forEach(col => {
      // 处理dataIndex为空的情况(比如示例中的Comments列)
      const targetKey = col.dataIndex || 'comments';
      newItem[targetKey] = item[targetKey] ?? ''; // 空值替换为空字符串,优化导出显示
    });
    return newItem;
  });
};

// 原始数据和列配置
const data = [{
    "ltoId": null,
    "updatedOn": "2022-02-15T11:08:29Z",
    "updatedBy": "Randy",
    "comments": null,
    "dan": "657904/865",
    "lotNo": null,
    "volumeNo": "6",
    "folioNo": "5",
    "bookNo": "5",
    "pageNo": "7",
    "optedInPt": null,
    "optedInDate": "2022-03-04T19:06:54Z",
    "status": "FINALIZED"
  },
  {
    "ltoId": "S94182/137",
    "updatedOn": "2021-10-21T20:42:46Z",
    "updatedBy": "Gene",
    "comments": false,
    "dan": "608161/966",
    "lotNo": "0",
    "volumeNo": "6",
    "folioNo": "4",
    "bookNo": "8",
    "pageNo": "1",
    "optedInPt": false,
    "optedInDate": "2021-12-25T20:11:58Z",
    "status": "PENDING"
  }
];

const columns = [{
    title: 'DAN',
    dataIndex: 'dan',
  },
  {
    title: 'LTO ID',
    dataIndex: 'ltoId',
  },
  {
    title: 'Proposed Lot No',
    dataIndex: 'lotNo',
  },
  {
    title: 'Volume No',
    dataIndex: 'volumeNo',
  },
  {
    title: 'Folio No',
    dataIndex: 'folioNo',
  },
  {
    title: 'Book No',
    dataIndex: 'bookNo',
  },
  {
    title: 'Page No',
    dataIndex: 'pageNo',
  },
  {
    title: 'Opted in PT',
    dataIndex: 'optedInPt',
  },
  {
    title: 'Opt-in date',
    dataIndex: 'optedInDate',
  },
  {
    title: 'Transaction status',
    dataIndex: 'status',
  },
  {
    title: 'Updated on',
    dataIndex: 'updatedOn',
  },
  {
    title: 'Updated by',
    dataIndex: 'updatedBy',
  },
  {
    title: 'Comments',
    dataIndex: '',
  }
];

// 转换后的数据和导出用的表头
const formattedData = transformDataForExport(data, columns);
const exportHeaders = columns.map(col => col.title);

// 直接使用formattedData和exportHeaders调用插件导出方法即可
console.log(formattedData, exportHeaders);

函数逻辑说明

  • 遍历原始数据数组,为每个数据项生成新对象
  • 严格按照columns数组的顺序,依次将对应dataIndex的属性添加到新对象中
  • 针对dataIndex为空的列,手动指定对应字段名,确保导出时表头与数据一一对应
  • 用?? ''将null/undefined替换为空字符串,避免Excel中显示不友好的空值标记

内容的提问来源于stack exchange,提问作者Negin Basiri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 08:15:34