寻找一种方法来添加"导出到CSV"按钮到一个反应表,它是一个npmjs包(https://www.npmjs.com/package/react-table)。
我需要添加一个自定义按钮,用于将表格数据导出为csv或xls格式的Excel工作表吗?
答案 0 :(得分:18)
看看这个npm库 - https://www.npmjs.com/package/react-csv
例如 -
import {CSVLink, CSVDownload} from 'react-csv';
const csvData =[
['firstname', 'lastname', 'email'] ,
['John', 'Doe' , 'john.doe@xyz.com'] ,
['Jane', 'Doe' , 'jane.doe@xyz.com']
];
<CSVLink data={csvData} >Download me</CSVLink>
// or
<CSVDownload data={csvData} target="_blank" />
答案 1 :(得分:16)
尽管公认的答案是正确的,但要使集成无缝化还需要做更多的工作。这是集成的样子
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;
这同样适用于过滤器。
答案 2 :(得分:1)
我认为我会通过简化的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;
}, {})
);
通过添加其他export
函数,我使用它来允许一个组件中的多个表导出。