# npm 安装
npm install --save xlsx file-saver
# 引入 FileSaver 和 XLSX
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
# 添加 exportExcel() 方法
exportExcel() {
/* table关联导出的dom节点 */
let wb = XLSX.utils.table_to_book(document.querySelector("#table"));
/* get binary string as output */
let wbout = XLSX.write(wb, {
bookType: "xlsx",
bookSST: true,
type: "array"
});
// "数据" 可自定义命名
try {
FileSaver.saveAs(
new Blob([wbout], { type: "application/octet-stream" }),
"数据.xlsx"
);
} catch (e) {
if (typeof console !== "undefined") console.log(e, wbout);
}
return wbout;
}
这里的“table”是表格的id
# 给按钮添加点击方法
<el-button size="small" type="success" @click="exportExcel()">导出 Excel</el-button>
# 完整代码
<template>
<div>
<el-button size="small" type="success" @click="exportExcel()">导出 Excel</el-button>
<el-table
:data="tableData"
border
show-summary
style="width: 100%;"
id="table">
<el-table-column
prop="date"
label="日期">
</el-table-column>
</el-table>
</div>
</template>
<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
name: "dome",
methods: {
exportExcel() {
/* table关联导出的dom节点 */
let wb = XLSX.utils.table_to_book(document.querySelector("#table"));
/* get binary string as output */
let wbout = XLSX.write(wb, {
bookType: "xlsx",
bookSST: true,
type: "array"
});
// "数据" 可自定义命名
try {
FileSaver.saveAs(
new Blob([wbout], { type: "application/octet-stream" }),
"数据.xlsx"
);
} catch (e) {
if (typeof console !== "undefined") console.log(e, wbout);
}
return wbout;
}
}
};
</script>
<style scoped>
</style>
参考博客: