1.首先下載 js-export-excel
npm install js-export-excel;
2.下載 xlsx
npm install xlsx;
3.引入
import * as XLSX from 'xlsx'
import ExportJsonExcel from 'js-export-excel'
4.定義方法
downloadFileToExcel = () => {
let option = {}; //option代表的就是excel文件
option.fileName = 'demo表'; //excel文件名稱
option.datas = [
{
sheetData: this.state.dataTable, //excel文件中的數據源
sheetName: 'demo', //excel文件中sheet頁名稱
sheetFilter: ['你的名稱', '我的名稱', '你的編號', '我的方案'], //excel文件中需顯示的列數據
sheetHeader:['你的名稱', '我的名稱', '你的編號', '我的方案'] //excel文件中每列的表頭名稱
}
]
let toExcel = new ExportJsonExcel(option); //生成excel文件
toExcel.saveExcel(); //下載excel文件
}
5.調用后台接口獲取數據源
axios.post('后台接口地址').then(res=>{
this.state.dataTable = [];
data.map(item=>{
// 表頭一一對應
this.state.dataTable.push(
{
'你的名稱':item.YourName,
'我的名稱':item.MyName,
'你的編號':item.YourNo,
'我的方案':item.MyNo
}
)
})
// 調用導出excel方法
this.downloadFileToExcel()
})
這樣就完完整整的實現了前端導出excel的方法了