实现目标:通过前端直接导出页面显示的table
//xlsx 与 file-saver依赖
npm install --save xlsx file-saver
// 引入导出Excel表格依赖
import FileSaver from "file-saver";
import XLSX from "xlsx";
<el-button @click="exportExcel" >导出结果</el-button>
<el-table :data="tableData" style="width: 95%; margin-left: 2%" height="540px" id="out-table">
<el-table-column prop="workShopName" label="车间" min-width="130"> </el-table-column>
<el-table-column prop="yizong" label="I 级总数"> </el-table-column>
<el-table-column prop="erzong" label="Ⅱ 级总数"> </el-table-column>
<el-table-column prop="yichuli" label="I 级处理"> </el-table-column>
<el-table-column prop="erchuli" label="Ⅱ 级处理"> </el-table-column>
<el-table-column prop="weichuli" label="未处理"> </el-table-column>
<el-table-column prop="chulilv" label="处理率"> </el-table-column>
</el-table>
//methods 导出方法
exportExcel () {
/* generate workbook object from table */
var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'))
/* get binary string as output */
var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
try {
FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '数量统计分析.xlsx')
} catch (e) {
if (typeof console !== 'undefined') console.log(e, wbout)
}
return wbout
},
这里需要注意 如果提示以下报错
Error: Cannot read properties of undefined (reading 'utils')
//将引入改为
import * as XLSX from 'xlsx'