在vue ,element 下用 xlsx +FileSaver 做前端导出

主要是两个依赖

npm install --save xlsx file-saver
//然后在组件引入
import FileSaver from 'file-saver'
import XLSX from 'xlsx'

然后在methods里写一个导出方法

exportExcel () {
//.tabelCss 是要导出的表格class
   let wb = XLSX.utils.table_to_book(document.querySelector('.tabelCss'))
   
    let wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
    try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'sheetjs.xlsx')
    } catch (e) { 
if (typeof console !== 'undefined') console.log(e, wbout)
}
    return wbout
}

很简单,这就可以了。
但是在使用中,遇到一个问题在导出一份表格的时候发现 !一样的数据导了两遍??

后来从网上发现 使用了el-table的fixed属性来让某一列固定造成的,但elementui的实现方式是:创建了两个tabledom,通过一个隐藏一个显示来实现交互效果。当我导出整个el-table 就会将两个div内的table都导出,导致数据重复
修改如下

exportExcel () {
let wb = XLSX.utils.table_to_book(document.querySelector('.tabelCss'))
let fix = document.querySelector('.tabelCss > .el-table__fixed-right')

if (fix) {
        wb = XLSX.utils.table_to_book(document.querySelector('.tabelCss').removeChild(fix))
        document.querySelector('.tabelCss').appendChild(fix)
} else {
        wb = XLSX.utils.table_to_book(document.querySelector('.tabelCss'))
          }

  let wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
    try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'sheetjs.xlsx')
            } catch (e) { 
                          if (typeof console !== 'undefined') console.log(e, wbout)
                       }
                               return wbout
            }

操作没问题,只是在转换时先移除,下一步append,其实直接导出fixed的table也可以,但是不能够兼容其他页面没有使用fixed的表格

你可能感兴趣的:(在vue ,element 下用 xlsx +FileSaver 做前端导出)