首先在項目中安裝js-export-excel插件,進入項目目錄,執行以下命令:
npm安裝:npm install --save js-export-excel
,
yarn安裝:yarn add js-export-excel
,
安裝好之後,查看package.json文件夾中會在dependencies
(生產環境依賴)對象中顯示插件版本信息:
//package.json
"dependencies": {
"@antv/data-set": "^0.10.0",
"@babel/runtime": "^7.2.0",
"antd": "^3.11.6",
"bizcharts": "^3.4.2",
"bizcharts-plugin-slider": "^2.1.1-beta.1",
"chalk": "^2.4.2",
"classnames": "^2.2.6",
"dva": "^2.4.0",
"enquire-js": "^0.2.1",
"hash.js": "^1.1.5",
"js-export-excel": "^1.1.2", //依賴安裝完成後顯示
"lodash": "^4.17.10",
"lodash-decorators": "^6.0.0",
"react": "^16.6.3",
"react-container-query": "^0.11.0",
"react-copy-to-clipboard": "^5.0.1",
"react-document-title": "^2.0.3",
"react-dom": "^16.6.3",
"react-fittext": "^1.0.0",
"react-media": "^1.8.0",
"react-router-dom": "^4.3.1"
},
將table數據導出爲excel文件的邏輯代碼:
//index.jsx
import React, { PureComponent } from 'react';
import { Table, Button } from 'antd';
import { connect } from 'dva';
import { formatTime } from '@/utils/utils';
import ExportJsonExcel from 'js-export-excel';
@connect(state => {
return {
loading: state.loading.models.getRepaymentPlanList,
getRepaymentPlanList: state.getRepaymentPlanList,
};
})
export default class extends PureComponent {
//導出爲excel文件的方法
downloadFileToExcel = () => {
const { getRepaymentPlanList } = this.props; //從props中獲取數據源
let option = {}; //option代表的就是excel文件
let dataTable = []; //excel文件中的數據內容
if (getRepaymentPlanList && getRepaymentPlanList.length > 0) {
for (let i in getRepaymentPlanList) { //循環獲取excel中每一行的數據
let _planDay = formatTime(getRepaymentPlanList[i].planDay, true); //格式化日期(自定義方法)
let obj = {
'還款期數': getRepaymentPlanList[i].planPeriod,
'計劃還款日': _planDay,
'租金(元)': getRepaymentPlanList[i].currentAmount,
'還款本金': getRepaymentPlanList[i].currentPrinciple,
'還款利息': getRepaymentPlanList[i].currentInterest,
}
dataTable.push(obj); //設置excel中每列所獲取的數據源
}
}
option.fileName = '實際還款計劃'; //excel文件名稱
option.datas = [
{
sheetData: dataTable, //excel文件中的數據源
sheetName: '實際還款計劃', //excel文件中sheet頁名稱
sheetFilter: ['還款期數', '計劃還款日', '租金(元)', '還款本金', '還款利息'], //excel文件中需顯示的列數據
sheetHeader: ['還款期數', '計劃還款日', '租金(元)', '還款本金', '還款利息'], //excel文件中每列的表頭名稱
}
]
let toExcel = new ExportJsonExcel(option); //生成excel文件
toExcel.saveExcel(); //下載excel文件
}
render() {
return (
<>
<h2 style={{ textAlign: 'center', fontSize: '24px' }}>實際還款計劃</h2>
<div style={{ width: "80%", margin: "0 auto" }}>
<Button type="primary" onClick={this.downloadFileToExcel} style={{ marginBottom: "15px" }}>下載</Button>
<Table
bordered
rowKey={record => record.id}
style={{ background: 'white' }}
columns={columns}
dataSource={getRepaymentPlanList}
pagination={false}
size='middle'
/>
</div>
</>
)
}
}
使用插件js-export-excel並不能將頁面中的table表格直接導出爲excel文件,而是我們自定義一個導出爲excel文件的方法,其中使用的數據源與頁面的table表格的數據源一致,然後進行拼接;這樣的隱式綁定方法在頁面看來像是將table數據直接導出爲excel文件,一旦導出excel方法中寫錯一個字段,那table數據和excel文件數據就會不一致,而且問題不容易排查,只能去代碼裏面一行一行排查代碼。
頁面效果圖,點擊下載按鈕之後會自動下載excel文件:
打開excel文件,內容可編輯: