一、安装xlsx和filesaver
npm install --save xlsx file-saver
二、在表格组件中引入安装的2个文件
import FileSaver from "file-saver"; import XLSX from "xlsx";
三、HTML结构
代码语言:javascript复制 <el-table :data="tableData3" style="width: 500px" height="250" id="table">
<el-table-column fixed prop="date" label="日期" width="150"></el-table-column>
<el-table-column prop="name" label="姓名" width="120"></el-table-column>
<el-table-column prop="province" label="省份" width="120"></el-table-column>
<el-table-column prop="city" label="市区" width="120"></el-table-column>
<el-table-column prop="address" label="地址" width="300"></el-table-column>
<el-table-column prop="zip" label="邮编" width="120"></el-table-column>
</el-table>
<el-button type="success" style="margin-top:20px;" @click="exportExcel">导出</el-button>
四、导出的方法
代码语言:javascript复制 methods: {
exportExcel() {
// out-table 关联导出的DOM节点
var fixed = document.querySelector(".el-table__fixed");
var excelTitle = "标题";
var wb = XLSX.utils.table_to_book(document.querySelector("#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" }),
excelTitle ".xlsx"
);
} catch (e) {
if (typeof console !== "undefined") console.log(e, wbout);
}
return wbout;
}
}
在页面点击导出按钮时可以正常导出,但是如果左边有固定的列,相同的数据会导出2遍,可以做如下修改:
代码语言:javascript复制 methods: {
exportExcel() {
// table 关联导出的DOM节点
var fixed = document.querySelector(".el-table__fixed");
var wb;
var excelTitle = "标题";
if (fixed) {
wb = XLSX.utils.table_to_book(
document.querySelector("#table").removeChild(fixed)
);
document.querySelector("#table").appendChild(fixed);
} else {
wb = XLSX.utils.table_to_book(document.querySelector("#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" }),
excelTitle ".xlsx"
);
} catch (e) {
if (typeof console !== "undefined") console.log(e, wbout);
}
return wbout;
}
}