<template> <div class="export_tools"> <div v-show="false"> <el-table id="out-table" style="width: 100%;" :data="exportTable"> <template v-for="(item, index) in exportTitle"> <el-table-column v-if="item.isExport" :prop="item.prop" :label="item.label" align="center" :key="index" > <template slot-scope="scope"> <span>{{ scope.row[item.prop] ? scope.row[item.prop] : '-' }}</span> </template> </el-table-column> </template> </el-table> </div> <div class="export_btn"> <el-button type="primary" @click="export_data" icon="el-icon-download">导出</el-button> </div> </div> </template> <script> /** * 组件说明:需要从父组件中传入三个值,如下 * 1、exportTable:需要导出的表格数据; * 2、exportTitle:表格中有哪些列是可以导出的;格式如下(isExport为true则导出此列,false则不导出此列): * [ * { * prop:'对应的字段1', * label:'列名1', * isExport: true * }, * { * prop:'对应的字段2', * label:'列名2', * isExport: false * } * ] * 3、excelName:导出的文件名,最后导出后文件的格式为:年-月-日 时_分_秒-excelName.xlsx, * 如 excelName 为 ‘通道数据表格’,则最后导出的文件名是:2022-01-14 10_40_52-通道数据表格.xlsx */ import FileSaver from 'file-saver' import XLSX from 'xlsx' export default { name: 'ExportExcel', props: { exportTable: { type: Array, required: true, default: [], }, exportTitle: { type: Array, required: true, default: [], }, excelName: { type: String, required: true, default: 'Data', }, }, data() { return {} }, methods: { // 导出 excel 表格 export_data() { if (this.exportTable.length == 0) return this.$message.warning('表格为空,无法导出...') // 为el-table添加一个id:out-table let wb = XLSX.utils.table_to_book(document.querySelector('#out-table')) let wbout = XLSX.write(wb, { bookType: 'xlsx', // 导出的文件类型 bookSST: true, type: 'array', }) try { FileSaver.saveAs( new Blob([wbout], { type: 'application/octet-stream' }), `${this.$dayjs().format('YYYY-MM-DD HH_mm_ss')}-${this.excelName}.xlsx` ) setTimeout(() => { return this.$message.success('表格导出成功...') }, 1000) } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) } return wbout }, }, mounted() {}, } </script> <style lang="scss" scoped> .export_tools { .export_btn { display: flex; padding-top: 10px; justify-content: center; } } </style>
然后在父组件中使用:
import ExportExcel from '../commonTools/ExportExcel.vue' // 引入导出表格组件
components: { 'export-excel': ExportExcel, // 注册组件 },
<export-excel :exportTable="tableData" :excelName="excel_name" :exportTitle="export_title" ></export-excel>
注意:需要先安装依赖:
npm install --save xlsx file-saver