关于el-table前端导出
面向百度编程的小菜鸟,有好的方法,希望大佬多多指教
新建一个js文件,创建导出的方法。
import FileSaver from "file-saver";
import XLSX from "xlsx";
//导出方法
export function exportInfo(tableId,name) { //此处的入参是表格的id ,name是导出时的名称
console.log("导出")
var wb = XLSX.utils.table_to_book(
document.querySelector("#" + tableId ),
);
var wbout = XLSX.write(wb, {
bookType: "xlsx",
bookSST: true,
type: "array",
});
try {
FileSaver.saveAs(
new Blob([wbout], { type: "application/octet-stream" }),
name + ".xlsx" //下载的时候默认的名称
);
} catch (e) {
if (typeof console !== "undefined") {
console.log(e, wbout);
}
}
return wbout;
}
2.添加导出按钮,并且给表格取一个id
<el-form style="margin: 10px 0">
<el-form-item label="">
<el-button type="primary" @click="download('exportTable')"> 导出</el-button>
</el-form-item>
</el-form>
<el-table :data="tableData" id=“exportTable”>
<el-table-column type="index" label="序号" width="50" align="center">
</el-table-column>
</el-table>
3.因为数据在后端经过了分页,所以我问要根据刚开始加载表格数据的总条数查询全部数据
//首先要将js中的方法引入
import { exportInfo } from '@/utils/export' //引入js
//获取导出的数据
async exportData (tableId) {
this.queryForm.pageSize = this.dataTotal;
await this.requestName({ //调用数据接口
...this.queryForm,
}).then((res) => { //成功回调函数
this.tableData = res.data.data;
})
var name = “....” + "详情";
//调用js导出方法
exportInfo(tableId,name);
},
//详情导出
download(tableId) {
this.tableData = [];
//调用导出方法
this.exportData(tableId)
this.queryForm.pageSize = 10;
},