vue2.5 + element UI el-table out of Excel

Installation depends

npm install --save xlsx file-saver

New excelHelper.js

  • \src\utils\New directory excelHelper.jsfile
import Vue from 'vue'
import FileSaver from "file-saver";
import XLSX from "xlsx";

export default {
    /**
     * @param tableId 要导出的表格ID
     * @param fileName 文件导出名称
     * @param fileType 文件类型
     * @param rawFlag - true 导出的内容只做解析,不进行格式转换
     * @returns {*}
     */
    exportExcel(tableId,fileName,fileType,rawFlag) {
        let fix = document.querySelector('.el-table__fixed');
        let wb;
        /* 判断要导出的节点中是否有fixed的表格,如果有,转换excel时先将该dom移除,然后append回去 */
        if(fix){ 
            wb = XLSX.utils.table_to_book(document.querySelector("#"+tableId).removeChild(fix),{raw:rawFlag});
            document.querySelector("#"+tableId).appendChild(fix);
        }else{
            wb = XLSX.utils.table_to_book(document.querySelector("#"+tableId),{raw:rawFlag});
        }
        /* 获取二进制字符串作为输出 */
        let wbout = XLSX.write(wb, {
            bookType: "xlsx",
            bookSST: true,
            type: "array"
        });
        try {
            FileSaver.saveAs(
                //Blob 对象表示一个不可变、原始数据的类文件对象。
                //Blob 表示的不一定是JavaScript原生格式的数据。
                //File 接口基于Blob,继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
                //返回一个新创建的 Blob 对象,其内容由参数中给定的数组串联组成。
                new Blob([wbout], { type: "application/octet-stream" }),
                //设置导出文件名称
                fileName + fileType
            );
        } catch (e) {
            if (typeof console !== "undefined") console.log(e, wbout);
        }
        return wbout;
    }
}

transfer

  • References need to use the Export pagesexcelHelper.js
import excelHelper from "@/utils/excelHelper";
  • Button calls
excelHelper.exportExcel("table","fileName",".xls",true);
  • Which tableis bound to a table id, fileNameis exported file name, .xlsis exported file type, truespecify the content of the exported only resolved without performing format conversion

Filled pit Guide

el-table data export Excel data repeated twice
  • The reason: el-table of fixed property to make a column fixed, but elementui implementation is: create two tabledom, through a display to achieve a hidden interaction effect, when export the entire el-table will be within two div the table are exported, resulting in duplication of data
  • Solution:
  let fix = document.querySelector('.el-table__fixed');
  let wb;
  //判断要导出的节点中是否有fixed的表格,如果有,转换excel时先将该dom移除,然后append回去
  if(fix){ 
    wb = XLSX.utils.table_to_book(document.querySelector('#table').removeChild(fix));
    document.querySelector('#table').appendChild(fix);
  }else{
    wb = XLSX.utils.table_to_book(document.querySelector('#table'));
  }

Recommended blog: https://blog.csdn.net/qq_40614207/article/details/94003793

Guess you like

Origin www.cnblogs.com/maggieq8324/p/12051429.html