首先表格导出需要使用到js-xlsx库,vue通过npm install xlsx安装后使用important XLSX from 'xlsx'导入
代码片段:
----------------html------------------------------
<el-button class="btn" type="primary" @click="onExport">导出</el-button>
<el-table
ref="filterTable" @row-click="rowClickHandle" :data="tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)" //数据分页显示
>
<el-table-column show-overflow-tooltip prop="name" label="名称" ></el-table-column> <el-table-column show-overflow-tooltip prop="address" label="地址" ></el-table-column> <el-table-column show-overflow-tooltip label="状态"> <template slot-scope="scope"> <span v-if="scope.row.statu == 0">待完成</span> <span v-if="scope.row.statu == 1">已完成</span> </template> </el-table-column> <el-table-column show-overflow-tooltip label="操作" v-if="oprationShow" > <template slot-scope="scope"> <span style="cursor: pointer" @click.stop="edit(scope)" >编辑</span> <span style="cursor: pointer" @click.stop="del(scope)" >删除</span> </template> </el-table-column>
</el-table> <el-pagination layout="total,prev, pager, next" :total="total" :page-size="pageSize" @current-change="changePage" > </el-pagination>
------------------------js--------------------------------
onExport() { this.oprationShow = false //不显示操作按钮 this.pageSize = this.total //将表格长度变成数据总长度 this.currentPage = 1 //显示第一页 this.$nextTick(function () { let wb = XLSX.utils.table_to_book(this.$refs.filterTable.$el); let wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' }); try {
//Blob
对象表示一个不可变、原始数据的类文件对象。它的数据可以按文本或二进制的格式进行读取,也可以转换成ReadableStream
来用于数据操作 _global.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '表格.xlsx') } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) } this.pageSize = 13 //表格长度还原 this.oprationShow = true //显示操作按钮 return wbout; }) },
changePage(currentPage){
this.currentPage = currentPage;
},
遇到的问题:
1.js-xlsx方法只能导出表格dom元素所显示的数据,分页的数据无法导出
解决方法:将表格在导出时不进行分页,所有数据都显示在第一页
2.表格的操作按钮不需要导出
解决办法:将表格导出时隐藏操作按钮当前列