File-Saver插件:El-Table表格數據導出到Excel表格


一、引入插件

  1、npm命令引入插件依賴:

cnpm install --save xlsx file-saver

  

  2、頁面引入

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

二、使用插件導出數據

  1、給El-Table加id:

<!-- 表格1 -->
<el-table :data="tableData" border height="750px" id="table1">
    <el-table-column :prop="item.value" :key="item.value" :label="item.label" v-for="item in column" v-if="item.show" :width="item.width"></el-table-column>
</el-table>
<!-- 表格2 -->
<el-table :data="tableData" border height="750px" id="table2">
    <el-table-column :prop="item.value" :key="item.value" :label="item.label" v-for="item in column" v-if="item.show" :width="item.width"></el-table-column>
</el-table>

  2、觸發導出事件:

  (1)參數method為需要導出的表格id

  (2)經過去除fixed元素操作來避免數據因為El-Table里的分表而重復導出

  (3)wb = XLSX.utils.table_to_book(table,{raw:true})中的raw:true表示不自動獲取格式,統一按照文本格式導出,可以有效避免超過12位的數字導出后變成科學記數法的問題。

    handleExportVue(method){
        // 判斷要導出的節點中是否有fixed的表格,如果有,轉換excel時先將該dom移除,然后append回去,避免導出的數據重復
        let fixRight = document.querySelector("#"+method).querySelector('.el-table__fixed-right');
        let fixLeft = document.querySelector("#"+method).querySelector('.el-table__fixed-left');
        let wb = null;
        let table = document.querySelector("#"+method);
        if (fixRight || fixLeft) {
          if(fixRight){
            table = table.removeChild(fixRight);
          }
          if(fixLeft){
            table = table.removeChild(fixLeft);
          }
          wb = XLSX.utils.table_to_book(table,{raw:true});
          if(fixRight){
            document.querySelector("#"+method).appendChild(fixRight);
          }
          if(fixLeft){
            document.querySelector("#"+method).appendChild(fixLeft);
          }
        } else {
          wb = XLSX.utils.table_to_book(table,{raw:true});
        }
        //獲取二進制字符串作為輸出
        let wbout = XLSX.write(wb, {
          bookType: "xlsx",
          bookSST: true,
          type: "array"
        });
        try {
          if(method == 'table1'){
            //設置導出文件名稱
            FileSaver.saveAs(new Blob([wbout], { type: "application/octet-stream" }), "表格1.xlsx");
          }else if(method == 'table2'){
            //設置導出文件名稱
            FileSaver.saveAs(new Blob([wbout], { type: "application/octet-stream" }), "表格2.xlsx");
          }
        } catch (e) {
          if (typeof console !== "undefined") console.log(e, wbout);
        }
        return wbout;
      }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM