1.安装相关依赖(file-saver,xlsx)
npm install xlsx@0.16.0 --save
npm install file-saver@2.0.2 --save
最好使用上述这两个版本,本人亲测不会版本冲突,下图就是版本冲突的报错,要及时进行规避。
2.在main.js中进行全局引入
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
Vue.prototype.$FileSaver = FileSaver; //设置全局
Vue.prototype.$XLSX = XLSX; //设置全局
3.表格相关代码并设置id
<el-table size="small" id="table-list" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
<el-table-column align="center" type="selection" width="60">
</el-table-column>
<el-table-column sortable prop="deptName" label="部门名称" width="300">
</el-table-column>
<el-table-column sortable prop="deptNo" label="部门代码" width="300">
</el-table-column>
<el-table-column sortable prop="editTime" label="修改时间" width="300">
<template slot-scope="scope">
<div>{{scope.row.editTime|timestampToTime}}</div>
</template>
</el-table-column>
<el-table-column sortable prop="editUser" label="修改人" width="300">
</el-table-column>
</el-table>
4.定义按钮进行点击触发
<el-button size="small" type="primary" icon="el-icon-download" @click="exportData">导出</el-button>
5.点击事件触发后进行下载处理
exportData(){
let excelName = '表格的名称.xlsx';
var xlsxParam = { raw: true };//转换成excel时,使用原始的格式
// 克隆节点
let tables = document.getElementById("table-list").cloneNode(true);
// 判断是否为固定列,解决(为固定列时,会重复生成表格)
if (tables.querySelector('.el-table__fixed') !== null) {
tables.removeChild(tables.querySelector('.el-table__fixed'))
}
let table_book = this.$XLSX.utils.table_to_book(tables,xlsxParam);
var table_write = this.$XLSX.write(table_book, {
bookType: "xlsx",
bookSST: true,
type: "array"
});
try {
this.$FileSaver.saveAs(
new Blob([table_write], { type: "application/octet-stream" }),
excelName
);
} catch (e) {
if (typeof console !== "undefined") console.log(e, table_write);
}
return table_write;
}