vue+elementui 中el-table导出为Excel并封装组件
安装依赖:
//xlsx 与 file-saver依赖
npm install --save xlsx file-saver
封装组件(Excel.vue)直接上代码:
<template>
<div>
<el-button type="primary" style="background-color: #0086b3" @click="exportExcel">{{btn}}</el-button>
</div>
</template>
<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
name: "excel",
props: {
btn: {
type: String,
default: "导出excel表格",
},
//导出的文件名
excel: {
type: String,
default: "excel文件",
},
},
data() {
return {};
},
methods: {
exportExcel() {
/* generate workbook object from table */
//表名===》 element ui 里面的表头el-table 的class名(excel)
var wb = XLSX.utils.table_to_book(document.querySelector(".excel"));
/* 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" }),
`${this.excel}.xlsx`
);
} catch (e) {
if (typeof console !== "undefined") console.log(e, wbout);
}
return wbout;
},
},
};
</script>
调用组件
//利用父子组件传btn名
<Excel :btn="excel.btn" :excel="excel.name"></Excel>
<script>
import Excel from "@/components/Excel";
export default {
components: {
Excel,
},
data() {
return {
excel: {
btn: "导出excel表格",
name: "excel",
},
};
},
};
</script>