官方案例:https://sheetjs.com/demos/table.html
背景:在后台管理系統項目中,一般都會有將table表格導出為Excel,此文主要總結了如何實現該功能。
同學們,眼見為實,我們盤他。
vue項目中table展示

導出之后的excel表格展示:

一、安裝相關依賴
//xlsx 與 file-saver依賴 npm install --save xlsx file-saver
二、在main.js中引入以上安裝好的組件
// vue中導出excel表格模板 import FileSaver from 'file-saver' import XLSX from 'xlsx' Vue.prototype.$FileSaver = FileSaver; //設置全局 Vue.prototype.$XLSX = XLSX; //設置全局
三、在組件中 補齊html ,並且在methods中寫入方法
<template>
<div class="driver-list-main">
<el-table
id="out-table"
ref="multipleTable"
:data="tableData"
:header-cell-style="{background:'#ccc',color: ' #333'}"
:show-header="true"
style="width: 100%"
:highlightCurrentRow="true"
>
<el-table-column type="selection" width="55"></el-table-column>
<el-table-column label="日期" width="120">
<template slot-scope="scope">{{ scope.row.date }}</template>
</el-table-column>
<el-table-column prop="name" label="姓名" width="120"></el-table-column>
<el-table-column prop="address" label="地址" show-overflow-tooltip></el-table-column>
</el-table>
</div>
</template>
<script>
export default {
name: "driver-list-main",
data() {
return {
tableData: [
{
date: "2016-05-03",
name: "王小虎",
address: "上海市普陀區金沙江路 1518 弄"
},
{
date: "2016-05-02",
name: "王小虎",
address: "上海市普陀區金沙江路 1518 弄"
},
{
date: "2016-05-04",
name: "王小虎",
address: "上海市普陀區金沙江路 1518 弄"
},
{
date: "2016-05-01",
name: "王小虎",
address: "上海市普陀區金沙江路 1518 弄"
},
{
date: "2016-05-08",
name: "王小虎",
address: "上海市普陀區金沙江路 1518 弄"
},
{
date: "2016-05-06",
name: "王小虎",
address: "上海市普陀區金沙江路 1518 弄"
},
{
date: "2016-05-07",
name: "王小虎",
address: "上海市普陀區金沙江路 1518 弄"
}
]}
},
methods: {
// 點擊按鈕 導出excel表格:
export2Excel: function() {
let tables = document.getElementById("out-table");
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;
},
}
}
注意:
- this.$XLSX.utils.table_to_book中放的是table的dom節點
- sheetjs.xlsx導出的是表格的名字
- 別忘記在vue中引入element-ui哦,否則html中的報錯。
- 本人對技術知識點的一個總結和歸納。
