关于vue.js:vueelementUIeltable-数据导出Excel

11次阅读

共计 1663 个字符,预计需要花费 5 分钟才能阅读完成。

1. 装置依赖

//xlsx 与 file-saver 依赖
npm install --save xlsx file-saver`

https://github.com/SheetJS/js-xlsx
https://github.com/eligrey/FileSaver.js

2. 在须要的组件中引入

import FileSaver from 'file-saver'
import XLSX from 'xlsx'

3. .vue:

<el-table :data="checkOrderList" border id="out-table">
// 表格内容
</el-table>
<el-button type="primary" @click="exportExcel"> 点击导出 </el-button>

4.methods 中引入办法

exportExcel (id,title) {
  /* generate workbook object from table */
  var wb = XLSX.utils.table_to_book(document.querySelector(#out-table))
  /* get binary string as output */
  var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array'})
   try {FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), title+'.xlsx')
   } catch (e) {if (typeof console !== 'undefined') console.log(e, wbout) }
   return wbout
}

到这表格就能够导出了


5. 反复数据问题和分页

  • 若是表格有固定在页面右侧的列,须要去掉 fixed 成果,选择器是 .el-table__fixed-right,再到前面append 下来;若是表格有固定表头,选择器是.el-table__fixed,不然会导致数据导出两遍。
  • 若是表格有分页,我把表格的不分页的全副数据拿到 (pageSize 设置一个很大的数,如:1000000),在点击导出时将数据渲染到须要导出数据的表格中,等到导出实现后,再把之前的分页数据换过来。


解决办法:

exportExcel() {
            const data = this.checkOrderList
            this.checkOrderList = this.allCheckOrderList // 把不分页的所有数据都渲染到表格中
            const fix = document.querySelector('.el-table__fixed')
            let wb
            this.$nextTick(() => {if (fix) { // 判断要导出的节点中是否有 fixed 的表格,如果有,转换 excel 时先将该 dom 移除,而后 append 回去
                    wb = XLSX.utils.table_to_book(document.querySelector('#out-table').removeChild(fix))
                    document.querySelector('#out-table').appendChild(fix)
                } else {wb = XLSX.utils.table_to_book(document.querySelector('#out-table'))
                }
                const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array'})
                try {FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), '流水表.xlsx')
                } catch (e) {if (typeof console !== 'undefined') console.log(e, wbout)
                }
                this.checkOrderList = data // 复原表格的分页数据
                return wbout
            })
        },

正文完
 0