- 根據業務需求添加導出Excel功能,首先在vue下安裝相關依賴
npm install --save xlsx file-saver
- 然後在<script> </script> 塊中引入相關組件
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
- table列表如下,導出的Excel表頭將根據table列出的屬性進行匹配
<!--導出Excel表格 tableDataExcel:保存列表數據的數組 export-table: 爲el-table組件的id屬性值 -->
<div v-show="false">
<el-table :data="tableDataExcel"
id="export-table"
stripe style="width: 100%;">
<el-table-column label="安全帽xzsdv">
<template slot-scope="scope">
<span>{{scope.row.devId.substring(8, 18)}}</span>
</template>
</el-table-column>
<el-table-column prop="color" label="顏色">
</el-table-column>
<el-table-column prop="" label="工人">
<template slot-scope="scope">
<span>{{scope.row.worker !== undefined ? scope.row.worker.name : ""}}</span>
</template>
</el-table-column>
<el-table-column prop="" label="工種">
<template slot-scope="scope">
<span>{{scope.row.profession !== undefined ? scope.row.profession.name : ""}}</span>
</template>
</el-table-column>
</el-table>
</div>
- 具體實現方法如下 若遇到導出的Excel文檔中只有表頭,沒有相關數據信息,可能是因爲數據渲染到DOM組件需要一定的時間,在進行導出操作時使用延時函數再進行導出功能操作。
/**
* 導數據時,查詢所有列表集合,再進行導出操作
*/
async function exportDataToExcel() {
this.tableDataExcel = [];
const result = await findAllSafeHat(0, 0, 'NORMAL', '', '');
if (result.code === 1200) {
this.tableDataExcel = result.data.safetyHat;
this.exportOut();
// setTimeout(() => {
// this.exportOut();
// }, 2000)
}
}
function exportOut() {
this.$confirm('導出列表數據到Excel', '提示', {
type: 'warning',
confirmButtonText: '確認',
cancelButtonText: '取消'
}).then(async () => {
// 根據el-table組件的id屬性(export-table)獲取數據信息
let wb = XLSX.utils.table_to_book(document.querySelector('#export-table'));
let wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'});
try {
FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), 'safetyHat.xlsx')
} catch (e) {
if (typeof console !== 'undefined') console.log(e, wbout)
}
return wbout;
}).catch(() => {
this.$message({message: '您已取消導出Excel操作!', type: 'warning'})
});
}