我這里為了同學們好理解,把所有元素都寫到一個頁面,
1.第一步安裝插件
npm install file-saver
npm install xlsx
2.第二步在mian.js中設定全域
// vue中匯出excel表格模板
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
Vue.prototype.$FileSaver = FileSaver; //設定全域
Vue.prototype.$XLSX = XLSX; //設定全域
3.第三步使用
<template>
<div class="daochu">
<el-button @click="o" type="success" round>匯出</el-button>
<el-table
id="ou"
:data="tableData"
style="width: 100%"
:default-sort="{ prop: 'date', order: 'descending' }"
>
<el-table-column prop="date" label="日期" sortable width="180">
</el-table-column>
<el-table-column prop="name" label="姓名" sortable width="180">
</el-table-column>
<el-table-column prop="address" label="地址" :formatter="formatter">
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [
{
date: "2016-05-02",
name: "王小虎",
address: "上海市普陀區金沙江路 1518 弄",
},
{
date: "2016-05-04",
name: "王小虎",
address: "上海市普陀區金沙江路 1517 弄",
}
],
};
},
methods:{
o() {
let tables = document.getElementById("ou");
let table_book = this.$XLSX.utils.table_to_book(tables);
var table_write = this.$XLSX.write(table_book, {
bookType: "xlsx",
bookSST: true,
type: "array",
});
try {
this.$FileSaver.saveAs(
new Blob([table_write], { type: "application/octet-stream" }),
"sheetjs.xlsx"
);
} catch (e) {
if (typeof console !== "undefined") console.log(e, table_write);
}
return table_write;
},
}
}
</script>
可以看到已經匯出

實際作業中匯出按鈕單獨抽離出去做到可以復用才是比較合理的,不懂怎么劃分目錄結構的可以看我的vue專欄哦!?也可以通過下面公_號:前端老實人,進群跟小伙伴一起學習哦!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/299706.html
標籤:其他
