在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的表格

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容