el-table表格导出Excel+导出重复

Element组件库中的el-table表格导出需要的主要是两个依赖:(xlsx 和 file-saver)

1.安装相关依赖

npm install --save xlsx file-saver

2·组件里头引入

// 引入导出Excel表格依赖
import FileSaver from "file-saver";
import XLSX from "xlsx";

=> 注意: 因为版本原因,通过 import 方式引用可能是 undefined,可以改为一下方式

const XLSX = require('xlsx')
// 代码
<el-button @click="imports">导出</el-button>
<el-table data="data" id="table"></el-table>


// js部分
imports() {
 // 参数一:报表名称   参数二:需要导出表格的类名或id 
  this.exportExcel('测试数据', '#table')
},
exportExcel(name, id) {
      const XLSX = require('xlsx')
      // 解决生成重复数据-因为使用l fixed属性 注意表格的fixed是left还是right
      const tables = document.querySelector(`${id}`).cloneNode(true)
      // 复制一个dom节点,不影响原来的节点
      const div = document.createElement("div");
      // div.style.display = 'none'
      const table = div.appendChild(tables)
      const right = table.querySelector(`.el-table__fixed-right`);
      const left = table.querySelector(`.el-table__fixed-left`);
      // 删除重复节点
      if (right) table.removeChild(right)
      if (left) table.removeChild(left)
      // 删除操作列 columns-operation
      const operations = table.querySelectorAll(`.columns-operation`) || []
      if (operations.length > 0) {
        operations.forEach(item => item.remove());
      }
      const wb = XLSX.utils.table_to_book(table, {
        raw: true
      });
      const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
      try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), name + '.xlsx')
      } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
      return wbout
    }

 

posted @ 2022-06-16 16:04  花开丶良人归  阅读(695)  评论(0)    收藏  举报