项目里有个把表格导出为Excel的功能,使用的是react-html-table-to-excel实现的也很简单,记录一下。
1.实现过程
1.下载依赖:npm install --save react-html-table-to-excel
1 | npm install --save react-html-table-to-excel |
2.导入:import ReactHTMLTableToExcel from 'react-html-table-to-excel' //导表
1 | import ReactHTMLTableToExcel from 'react-html-table-to-excel' //导表 |
3.具体实现过程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | import React from 'react' import ReactDOM from 'react-dom' import ReactHTMLTableToExcel from 'react-html-table-to-excel' //导表 class TableExport extends React.Component { render( <div> <ReactHTMLTableToExcel id="test-table-xls-button" className="download-table-xls-button" table="table-to-xls" filename="tablexls" sheet="tablexls" buttonText="Download as XLS"/> <table id="table-to-xls"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Jill</td> <td>Smith</td> <td>50</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td>94</td> </tr> </table> </div> ) } |
Property | Type | Description |
---|---|---|
table | string | 表格名字 |
filename | string | 文件名字 |
sheet | string | excel的sheet名 |
id | string | id |
className | string | 类名 |
buttonText | string | Button text. |
4. antd Table导出:因为antd对table进行了封装所以需要借助ref属性来获取然后再设置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | import React from 'react' import ReactDOM from 'react-dom' import ReactHTMLTableToExcel from 'react-html-table-to-excel' //导表 import { Table } from 'antd'//导入Table组件 class TableExport extends React.Component { exportTable(){ const tableCon = ReactDOM.findDOMNode(this.refs['table']) //// 通过ref属性找到该table const table = tableCon.querySelector('table') ////获取table table.setAttribute('id', 'table-to-xls') //给该table设置属性 } render(){ <div> <button onClick={this.exportTable}>导出</button> <ReactHTMLTableToExcel id="test-table-xls-button" table="table-to-xls" filename="tablexls" sheet="tablexls" /> <Table ref="table" columns={this.columns} //替换成自己的 dataSource={this.state.data} //替换成自己的 /> </div> } } |
npm react-html-table-to-excel的官网网址API