当前位置: 首页 > 工具软件 > Table To Xls > 使用案例 >

react使用(react-html-table-to-excel)把table导出为Excel以及配合antd使用

魏健柏
2023-12-01

项目里有个把表格导出为Excel的功能,使用的是react-html-table-to-excel实现的也很简单,记录一下。

1.实现过程

1.下载依赖:npm install --save react-html-table-to-excel

npm install --save react-html-table-to-excel

2.导入:import ReactHTMLTableToExcel from 'react-html-table-to-excel' //导表

import ReactHTMLTableToExcel from 'react-html-table-to-excel' //导表

 3.具体实现过程

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

 

PropertyTypeDescription
tablestring 表格名字
filenamestring文件名字
sheetstringexcel的sheet名
idstringid
classNamestring类名
buttonTextstringButton text.

4. antd Table导出:因为antd对table进行了封装所以需要借助ref属性来获取然后再设置

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

 类似资料: