1.先安装依赖
npm install --save xlsx file-saver
2.在要导出的vue组件中的script引入
import FileSaver from "file-saver"
import XLSX from "xlsx"
3.导出方法
exportExcel() {//执行此方法导出Excel表格
// 为el-table添加一个id:out-table
// 当el-table使用了fixed时会导出两次数据,所以要先进行判断
var fix = document.querySelector('.el-table__fixed');
var wb;
if (fix) {
// 如果有fixed,先移除,然后再添加上
wb = XLSX.utils.table_to_book(document.querySelector("#out-table").removeChild(fix))
document.querySelector("#out-table").appendChild(fix)
}else{
wb = XLSX.utils.table_to_book(document.querySelector("#out-table"))
}
var wbout = XLSX.write(wb, {
bookType: "xlsx",
bookSST: true,
type: "array"
});
try {
FileSaver.saveAs(
new Blob([wbout], {
type: "application/octet-stream"
}),
// 导出的文件名称
"Data.xlsx"
)
} catch (e) {
if (typeof console !== "undefined") console.log(e, wbout);
}
return wbout;
},
这个方法也存在问题,比如样式不够灵活等。
非常感谢,牛啊