vue2.0 + element UI 中 el-table 数据导出Excel

2022-01-10

1、 安装相关依赖
npm install –save xlsx file-saver

2、组件里头引入
import FileSaver from ‘file-saver’
import XLSX from ‘xlsx’

3、写一个方法

// 导出excel表格文件
export function handleExportExcel() {
  // 如果表格中没有fixed属性固定列,直接取表格id就行
  // const table = document.querySelector(‘#outTable’)
  // 如果表格中有fixed属性固定列,需要像下面这样做一下处理,要不然下载的excel数据会重复2次!参考:https://blog.csdn.net/WYA1993/article/details/85319138
  const table = document.querySelector(‘#outTable’).cloneNode(true)
  if (table.querySelector(‘.el-table__fixed’)) {
    table.removeChild(table.querySelector(‘.el-table__fixed’))
  }
  var wb = XLSX.utils.table_to_book(table)
  var 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
}

注意:XLSX.uitls.table_to_book( 放入的是table 的DOM 节点 ) ,sheetjs.xlsx 即为导出表格的名字,可修改!

 

4.表格代码

<el-table id=”outTable” :data=”tableData” height=”500″ border style=”width: 100%”>

5.导出按钮添加点击事件,执行exportExcel()方法

<el-button type=”primary” @click=”exportExcel”>导出</el-button>

如果element-ui的table使用了fixed属性固定列,导出表格时会出现导出两次的问题,是因为在table中有两个table标签,我们可以通过代码解决这个问题,注意代码中拷贝了一个table元素,否则直接删除会删除页面中的表格。

参考:https://www.cnblogs.com/chr506029589/p/11454154.html#!comments
https://blog.csdn.net/WYA1993/article/details/85319138

发表评论

邮箱地址不会被公开。 必填项已用*标注