1、安装相关的依赖;(xlsx,file-saver)
npm install --save xlsx file-saver
2、在main.js里引入
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
Vue.prototype.$FileSaver = FileSaver; //设置全局
Vue.prototype.$XLSX = XLSX; //设置全局
3、设置表格的id
<el-table
id="out-table"
:header-cell-style="{
background: 'rgba(245,248,253,1)',
color: '#554'
}"
:row-style="{ height: '30px' }"
:cell-style="{ padding: '0px'}"
border
:data="tableData"
v-loading="loading"
stripe
>
<el-table>
4、导出按钮(触发)
<el-button
size="small"
type="primary"
icon="el-icon-download"
@click="exportData"
>导出</el-button>
5、下载处理
methods: {
//导出功能
exportData(){
let excelName = '导出表格名称.xlsx';
var xlsxParam = { raw: true };//转换成excel时,使用原始的格式
// 克隆节点
let tables = document.getElementById("out-table").cloneNode(true);
// 判断是否为固定列,解决(为固定列时,会重复生成表格)
if (tables.querySelector('.el-table__fixed') !== null) {
tables.removeChild(tables.querySelector('.el-table__fixed'))
}
//在这之前可以修改tables添加东西
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"
});
//在这可以操作table_write设置导出表格样式
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;
}
}