Javascript 反应表中的导出到 CSV 按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48760815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:14:33  来源:igfitidea点击:

Export to CSV button in react table

javascriptreactjsfrontendreact-table

提问by Zinngg

Looking for a way to add an "Export to CSV" button to a react-table which is an npmjs package (https://www.npmjs.com/package/react-table).

寻找一种将“导出到 CSV”按钮添加到作为 npmjs 包的 react-table 的方法(https://www.npmjs.com/package/react-table)。

I need to add a custom button for exporting the table data to an excel sheet in the csv or xls format?

我需要添加一个自定义按钮来将表格数据导出到 csv 或 xls 格式的 Excel 表格中吗?

回答by Rishikesh Dhokare

Take a look at this npm library - https://www.npmjs.com/package/react-csv

看看这个 npm 库 - https://www.npmjs.com/package/react-csv

For example -

例如 -

import {CSVLink, CSVDownload} from 'react-csv';

const csvData =[
  ['firstname', 'lastname', 'email'] ,
  ['John', 'Doe' , '[email protected]'] ,
  ['Jane', 'Doe' , '[email protected]']
];
<CSVLink data={csvData} >Download me</CSVLink>
// or
<CSVDownload data={csvData} target="_blank" />

回答by best wishes

Although the accepted answer is correct, but it needed more work to make the integration seamless. Here is how integration will look like

虽然接受的答案是正确的,但需要更多的工作才能使集成无缝。这是集成的样子

import React from 'react';
import 'react-dropdown/style.css'
import 'react-table/react-table.css'
import ReactTable from "react-table";
import {CSVLink} from "react-csv";

const columns = [
   {
       Header: 'name',
       accessor: 'name', // String-based value accessors!
   },
   {
       Header: 'age',
       accessor: 'age',

  }]
class AllPostPage extends React.Component {
    constructor(props) {
       super(props);
       this.download = this.download.bind(this);
       this.state = {
          tableproperties: {
             allData: [
                {"name": "ramesh","age": "12"},
                {"name": "bill","age": "13"},
                {"name": "arun","age": "9"},
                {"name": "kathy","age": "21"}
             ]
          },
          dataToDownload: []
       };
    }

   download(event) {
      const currentRecords = this.reactTable.getResolvedState().sortedData;
      var data_to_download = []
      for (var index = 0; index < currentRecords.length; index++) {
         let record_to_download = {}
         for(var colIndex = 0; colIndex < columns.length ; colIndex ++) {
            record_to_download[columns[colIndex].Header] = currentRecords[index][columns[colIndex].accessor]
         }
         data_to_download.push(record_to_download)
      }
      this.setState({ dataToDownload: data_to_download }, () => {
         // click the CSVLink component to trigger the CSV download
         this.csvLink.link.click()
      })
    } 

    render() {
       return <div>
                 <div>
                    <button onClick={this.download}>
                        Download
                    </button>
                 </div>
                 <div>
                    <CSVLink
                        data={this.state.dataToDownload}
                        filename="data.csv"
                        className="hidden"
                        ref={(r) => this.csvLink = r}
                        target="_blank"/>

                 </div>
                 <div>
                    <ReactTable ref={(r) => this.reactTable = r}
                                data={this.state.tableproperties.allData} columns={columns} filterable
                                defaultFilterMethod={(filter, row) =>
                                    String(row[filter.id]).toLowerCase().includes(filter.value.toLowerCase())}
                    />
                 </div>
              </div>
    }
}

export default AllPostPage;

This will work with filters as well.

这也适用于过滤器。

回答by Jeremy J Barth

I thought I'd piggyback on best wishes' extremely valuable answer with a simplified downloadimplementation.

我想我会通过一个简化的download实现来捎带最好的祝福非常有价值的答案。

  export = e => {
    const currentRecords = this.ReactTable.getResolvedState().sortedData;
    this.setState({ dataToDownload: this.dataToDownload(currentRecords, columns) }, () =>
      this.csvLink.link.click()
    );
  }

  dataToDownload = (data, columns) =>
    data.map(record =>
      columns.reduce((recordToDownload, column) => {
        recordToDownload[column.Header] = record[column.accessor];
        return recordToDownload;
      }, {})
    );

I used this to allow multiple table exports in one component by adding additional exportfunctions.

我使用它通过添加附加export功能在一个组件中允许多个表导出。