1、下载依赖:
npm install --save xlsx file-saver
2、在 /src 下 新建一个文件夹放编写的 js (outToExcel.js)
import FileSaver from 'file-saver';
import * as XLSX from 'xlsx'
export default {
exportExcel(name, tableName) {
var sel = XLSX.utils.table_to_book(document.querySelector(tableName))
var selIn = XLSX.write(sel, { bookType: 'xlsx', bookSST: true, type: 'array' })
try {
FileSaver.saveAs(new Blob([selIn], { type: 'application/octet-stream' }), name)
} catch (e) {
if (typeof console !== 'undefined') console.log(e, selIn)
}
return selIn
}
};
3、main.js里面引入刚刚写好的那个js文件
vue2.0写法
import 文件名 from 刚刚写好的那个js文件的路径
Vue.prototype.outToExcels(取名随意) = 文件名;
vue3.0写法
import 文件名from 路径;
createApp(App).config.globalProperties.outToExcels(取名随意) = 文件名;
4、methods方法调用
<el-table id="table"></el-table>
<el-button @click="outExcel"> 导出 </el-button>
methods:{
outExcel() {
//参数一:生成excel的文件名 参数二:表格的id
this.outToExcels.exportExcel("txt.xlsx","#table");
}
}