我这里为了同学们好理解,把所有元素都写到一个页面。
1.第一步安装插件
1.npm install file-saver npm install xlsx
2.第二步在mian.js中设置全局
1.// 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专栏哦!❤也可以通过下面公_号:前端老实人,进群跟小伙伴一起学习哦!