【vue】純前端導出表格數據(vue+element-ui)

1.安裝依賴

安裝依賴xlsx,file-saver

npm install --save xlsx file-saver

2.在組件中引入

import FileSaver from 'file-saver'
import XLSX from 'xlsx'

3.添加下載方法

#out-table爲table節點的id

    outTab () {
      /* 從表生成工作簿對象 */
            var xlsxParam = { raw: true } // 導出的內容只做解析,不進行格式轉換
            var wb = XLSX.utils.table_to_book(document.querySelector("#Console"), xlsxParam);
           /* 獲取二進制字符串作爲輸出 */
            var wbout = XLSX.write(wb, {
                bookType: "xlsx",
                bookSST: true,
                type: "array"
            });
            var date = this.getTime();
            try {
                FileSaver.saveAs(
                //Blob 對象表示一個不可變、原始數據的類文件對象。
                //Blob 表示的不一定是JavaScript原生格式的數據。
                //File 接口基於Blob,繼承了 blob 的功能並將其擴展使其支持用戶系統上的文件。
                //返回一個新創建的 Blob 對象,其內容由參數中給定的數組串聯組成。
                new Blob([wbout], { type: "application/octet-stream" }),
                //設置導出文件名稱
                // "sheetjs.xlsx"
                `${date} ${name}.xlsx`
                );
            } catch (e) {
                if (typeof console !== "undefined") console.log(e, wbout);
            }
            return wbout;
     },

4.注意點

使用el-table的filex屬性時,會導致生成2份數據
解決方法:

 /* generate workbook object from table */
let fix = document.querySelector('.el-table__fixed');
let wb;
if (fix) {
    wb = XLSX.utils.table_to_book(document.querySelector("#out-table").removeChild(fix));
    document.querySelector("#out-table").appendChild(fix);
} else {
    wb = XLSX.utils.table_to_book(document.querySelector("#out-table"));
}
/* get binary string as output */
let wbout = XLSX.write(wb, {
    bookType: 'xlsx',
    bookSST: true,
    type: 'array'
});

try {
  FileSaver.saveAs(new Blob([wbout], {
    type: 'application/octet-stream'
   }),  'file.xlsx');
} catch (e) {
  if (typeof console !== 'undefined') console.log(e, wbout)
}
return wbout;

文章轉自鏈接:https://www.jianshu.com/p/66a837c539ac

發佈了40 篇原創文章 · 獲贊 28 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章