【问题标题】:Data export using react-data-table-component export csv使用 react-data-table-component 导出数据导出 csv
【发布时间】:2022-09-25 21:52:29
【问题描述】:

我是 React 的新手。

我正在尝试将使用 \'react-data-table-component\' 显示的 JSON 数据导出到 CSV 文件。

我已经按照this link 中的示例复制了提供的确切代码 sn-p。下面是我的代码 sn-p 和编译过程中发生的相应错误。

import Export from \"react-data-table-component\"
import DataTable, { TableColumn, TableStyles } from \"react-data-table-component\";
import React from \"react\";

  ---code declarations---

  const actionsMemo = React.useMemo(() => <Export onExport={() => downloadCSV(customerList)} />, []);

  return (
    <>
      <Row>
        <Col lg={3}>
          <Box className=\"box\" sx={{ display: \'flex\', alignItems: \'flex-end\' }}>
          
            <TextField id=\"input-with-sx\" label=\"Input National ID\" variant=\"standard\" />
            <PersonSearchIcon sx={{ color: \'action.active\', mr: 1, my: 0.5 }} />
          </Box>
        </Col>
      </Row>
      <br/>
      <Row>
        <Col lg={12}>
          <div className=\"card mb-3\">
            <div className=\"card-body\">
              <DataTable columns={columns} data={customerList}
                pagination  customStyles={mycustomStyles} actions={actionsMemo}/>
            </div>
          </div>          
        </Col>
      </Row>
    </>
  );

有人可以帮助我识别我可能缺少的任何其他模块,以便具有导出数据功能。提前致谢。

    标签: javascript reactjs react-typescript react-data-table-component


    【解决方案1】:

    这实际上是一个进口问题。

    import Export from "react-data-table-component"
    

    在这一行中,您正在导入默认导出来自react-data-table-component 包并将其分配给变量Export。默认导出是 DataTable 组件,它没有 onExport 属性。


    没有从包中导出的Export 组件。您看到的是在其文档中使用的本地声明(未导出)Export 组件。

    const Export = ({ onExport }) => <Button onClick={e => onExport(e.target.value)}>Export</Button>;
    

    这是source file。它依赖于样式化的Button component。他们在这里使用e.target.value 对我来说没有任何意义。


    您可以通过将其中任何一个放入您的代码中来创建您自己的具有正确 TypeScript 类型的 Export 组件:

    简单版:

    export const Export = ({ onExport }: { onExport: () => void }) => (
      <button onClick={() => onExport()}>Export</button>
    );
    

    支持 HTML button 的任何属性(例如 classNamestyle):

    type ExportProps = {
      onExport: React.MouseEventHandler<HTMLButtonElement>;
    } & JSX.IntrinsicElements["button"];
    
    export const Export = ({ onExport, ...props }: ExportProps) => (
      <button {...props} onClick={onExport}>
        Export
      </button>
    );
    

    【讨论】:

    • 多亏了这一点,我能够按照建议通过创建自己的Export 组件来解决它。
    • 示例的源代码(为示例中的代码带来更多上下文)可以在这里找到:link
    【解决方案2】:

    对于这个问题,我有非常简单的解决方案。

    您可以尝试使用非常简单的方法将表格数据 json 转换为 csv 或 json 转换为 xlsx。

    我的示例代码是尝试将 json 转换为 xlsx:

      function downloadXLS() {
        const ws = XLSX.utils.json_to_sheet(this.myJsonDataArray);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "People");
        XLSX.writeFile(wb, 'reports.xlsx');
      }
    

    添加按钮下载:

    <Button onClick={() => downloadXLS()}>Export</Button>
    

    另一个解决方案是 csv 的数据数组:(我从之前的回复中得到了这段代码)

    function convertArrayOfObjectsToCSV(array) {
        let result;
    
        const columnDelimiter = ',';
        const lineDelimiter = '\n';
        const keys = Object.keys(data[0]);
    
        result = '';
        result += keys.join(columnDelimiter);
        result += lineDelimiter;
    
        array.forEach(item => {
            let ctr = 0;
            keys.forEach(key => {
                if (ctr > 0) result += columnDelimiter;
    
                result += item[key];
                // eslint-disable-next-line no-plusplus
                ctr++;
            });
            result += lineDelimiter;
        });
    
        return result;
    }
    
    
    function downloadCSV() {
        const link = document.createElement('a');
        let csv = convertArrayOfObjectsToCSV(this.myJsonDataArray);
        if (csv == null) return;
    
        const filename = 'export.csv';
    
        if (!csv.match(/^data:text\/csv/i)) {
            csv = `data:text/csv;charset=utf-8,${csv}`;
        }
    
        link.setAttribute('href', encodeURI(csv));
        link.setAttribute('download', filename);
        link.click();
    }
    

    添加按钮下载:

    <Button onClick={() => downloadCSV()}>Export</Button>
    

    【讨论】:

      猜你喜欢
      • 2023-01-09
      • 2020-09-28
      • 2023-04-07
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      • 2016-02-05
      • 1970-01-01
      • 2017-01-07
      相关资源
      最近更新 更多