项目中使用antd的Table组件,组件未提供导出Excel表格功能,但是这个功能又是比较常用的,于是便将该组件进行二次封装,使得组件在被调用时,直接配置导出按钮就可以讲数据导出
1.npm安装ExportJsonExcel
npm install js-export-excel
2.给表格组件添加按钮
{this.props.dataConfig.exportBtnShow === true ? (
<Button
onClick={() => this.downloadExcel()}
title="导出Excel表格"
className="btn"
type="primary"
>
导出全部
</Button>
) : null}
3.在表格组件中实现
// 导出Excel
downloadExcel() {
let option = {}
if (this.props.dataConfig.dataSource) {
// 文件名
option.fileName = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
option.datas = [
{
// 父组件传递的要导出的数据
sheetData: this.props.dataConfig.dataSource,
// sheet名字
sheetName: 'sheet',
//父组件传递过来的要导出的数据的key值是一个数组
sheetFilter: this.props.dataConfig.sheetDataFilter,
// Excel表格的表头,在父组件中传递的时候注意与key对应
sheetHeader: this.props.dataConfig.sheetDataHeader
}
]
}
// 创建一个ExportJsonExcel实例
const exportExcel = new ExportJsonExcel(option)
// 将数据保存到Excel并且导出
exportExcel.saveExcel()
}