- 1 安装依赖:xlsx、file-saver
npm install xlsx --save
npm install file-saver --save - 在src目录下新建mixins目录,新建MixinsExport.js文件
import { saveAs } from 'file-saver'
import { utils, write } from 'xlsx'
export default {
methods: {
// 点击按钮 导出excel表格:
exportToExcel (fileName = '') {
const tables = document.getElementById("out-table");
const fix = tables.querySelector('.el-table__fixed'); // 判断要导出的节点中是否有fixed的表格,如果有,转换excel时先将该dom移除,然后append回去,
let table_book;
if (fix) {
table_book = utils.table_to_book(tables.removeChild(fix), { raw: true });
tables.appendChild(fix)
} else {
table_book = utils.table_to_book(tables, { raw: true });
}
const table_write = write(table_book, {
bookType: "xlsx",
bookSST: true,
type: "array"
});
try {
saveAs(
new Blob([table_write], { type: "application/octet-stream" }),
fileName ? `${fileName}.xlsx` : `${new Date().getTime()}.xlsx`
);
} catch (e) {
if (typeof console !== "undefined") console.log(e, table_write);
}
return table_write;
},
}
}
- 页面使用
<template>
<div>
<el-button type="primary" size="mini" @click="exportToExcel()" icon="el-icon-download">
导出
</el-button>
<el-table id="out-table" :data="tableData" style="width: 100%">
<el-table-column prop="date" label="日期" width="180">
</el-table-column>
<el-table-column prop="name" label="姓名" width="180">
</el-table-column>
<el-table-column prop="address" label="地址">
</el-table-column>
</el-table>
</div>
</template>
<script>
import MixinsExport from "@/mixins/MixinsExport";
export default {
mixins: [MixinsExport],
data() {
return {
tableData: [{
date: '2016-05-02',
name: '王小虎',
address: '上海市普陀区金沙江路 1518 弄'
}, {
date: '2016-05-04',
name: '王小虎',
address: '上海市普陀区金沙江路 1517 弄'
}, {
date: '2016-05-01',
name: '王小虎',
address: '上海市普陀区金沙江路 1519 弄'
}, {
date: '2016-05-03',
name: '王小虎',
address: '上海市普陀区金沙江路 1516 弄'
}]
}
}
}
</script>
参考自:
https://blog.csdn.net/shiqi236/article/details/108321292
https://blog.csdn.net/weixin_42464544/article/details/94737511
https://blog.csdn.net/weixin_41542329/article/details/118696183