最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Data export using react-data-table-component export csv - Stack Overflow

programmeradmin1浏览0评论

I am new to React.

I am trying to export JSON data that is displayed using the 'react-data-table-ponent' to a CSV file.

I have followed the example from this link by copying the exact code snippet provided. Below is my code snippet and the corresponding error occurring during pilation.

import Export from "react-data-table-ponent"
import DataTable, { TableColumn, TableStyles } from "react-data-table-ponent";
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>
    </>
  );

Could someone help me in identifying any other modules that I may be missing in order to have an export data functionality. Thanks in advance.

I am new to React.

I am trying to export JSON data that is displayed using the 'react-data-table-ponent' to a CSV file.

I have followed the example from this link by copying the exact code snippet provided. Below is my code snippet and the corresponding error occurring during pilation.

import Export from "react-data-table-ponent"
import DataTable, { TableColumn, TableStyles } from "react-data-table-ponent";
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>
    </>
  );

Could someone help me in identifying any other modules that I may be missing in order to have an export data functionality. Thanks in advance.

Share Improve this question asked Feb 11, 2022 at 23:09 clinewtonclinewton 431 gold badge1 silver badge6 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

This is actually an import issue.

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

In this line right here, you are importing the default export from the react-data-table-ponent package and assigning it to the variable Export. The default export is the DataTable ponent, which does not have an onExport prop.


There is no Export ponent exported from the package. What you are seeing is a locally declared (not exported) Export ponent which is used in their documentation.

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

Here's the source file. It relies on a styled Button ponent. Their use of e.target.value here does not make any sense to me.


You can create your own Export ponent with proper TypeScript types by putting either of these in your code:

Simple version:

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

With support for any props of the HTML button (such as className and style):

type ExportProps = {
  onExport: React.MouseEventHandler<HTMLButtonElement>;
} & JSX.IntrinsicElements["button"];

export const Export = ({ onExport, ...props }: ExportProps) => (
  <button {...props} onClick={onExport}>
    Export
  </button>
);

I have very simple solution for this issue.

You can try to convert table data json to csv or xlsx with very simple methods.

My sample code is try to convert json to 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');
  }

Add button to download:

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

Another solution is data array to csv: (I got this code from previous response)

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();
}

Add button to download:

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

Based from Bilal Demir, this is my solution for React + react-data-table-ponent:

First install:

    npm install xlsx

Excel.tsx

import { utils, writeFileXLSX } from 'xlsx';
export const handleDownloadExcel = (dataSource:any,sheetName:string,fileName:string) => {
        const ws = utils.json_to_sheet(dataSource);
        const wb = utils.book_new();
        utils.book_append_sheet(wb, ws, sheetName);
        writeFileXLSX(wb, `${fileName}.xlsx`);        
    };

In Table View, react-bootstrap + react-data-table-ponent:

    import { handleDownloadExcel } from "../../../ponents/Excel";

    const downloadExcel = () => {
        handleDownloadExcel(dataSource,"SHEET_NAME","MY_FILENAME")  
    };
 

    <Container fluid className="form-group row mt-10">

    <Col>
        <Button type={'button'} className="btn-sm float-end mx-2" text="Excel" onClick={downloadExcel}  />           
        <DataTable
            columns={columns}
            data={dataSource}
            pagination               
            
        />
    </Col>
</Container>
发布评论

评论列表(0)

  1. 暂无评论