React 组件实现将 Ant Design Table 的展示结果导出 Excel

更新日期: 2024-10-11 阅读次数: 67 字数: 210 分类: ReactJS

使用 Antd Pro 实现了一个报价单批量查询的功能。

我想将 react 前端 table 组件的批量查询结果导出为 Excel 文件并下载。

这个不方便用后台接口实现,因为批量查询是通过多次的异步调用接口实现的。 后台并没有对应的一次性导出接口。

所以考虑采用前端实现的方案。

安装依赖

yarn add react-html-table-to-excel

react 代码

import ReactHTMLTableToExcel from 'react-html-table-to-excel';

const QuotationSearch: React.FC = () => {
  const exportExcel = () => {
    const cloneDivNode = document.getElementById('antdTable').cloneNode(true);
    const table = document.createElement('table');
    table.appendChild(cloneDivNode);
    table.setAttribute('id', 'table-to-xls');
    document.getElementById('root').appendChild(table);
    document.getElementById('test-table-xls-button').click();
    setTimeout(() => {
      document.getElementById('root').removeChild(table);
    }, 500);
  };

  return (
    <PageContainer>
      <div>
        <Space direction="vertical" size="middle" style={{ width: '100%' }}>
          <Button onClick={exportExcel} icon={<DownloadOutlined />}>
            导出 Excel
          </Button>
          <Table<API.Quotation>
            columns={columns}
            dataSource={results}
            id="antdTable"
          />
          <ReactHTMLTableToExcel
            id="test-table-xls-button"
            className="download-table-xls-button"
            table="table-to-xls"
            filename="报价单"
            sheet="Sheet1"
            buttonText=""
            style={{ visibility: 'hidden' }}
          />
        </Space>
      </div>
    </PageContainer>
  );
}

参考

  • https://zhuanlan.zhihu.com/p/353741518

微信关注我哦 👍

大象工具微信公众号

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式