前端讀取Excel表中資料

Turner發表於2018-12-08

Npm安裝js-xlsx庫

npm install js-xlsx
複製程式碼

在頁面中引入庫

import XLSX from "xlsx";
複製程式碼

程式碼

    upLoadMainFile(file) {   //傳入file
      let f = file;
      let reader = new FileReader();
      reader.onload = function(e) {
        let data = e.target.result;
        let wb;
        let o = "",
          l = 0,
          w = 10240;
        for (; l < data.byteLength / w; ++l)
          o += String.fromCharCode.apply(
            null,
            new Uint8Array(data.slice(l * w, l * w + w))
          );
        o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
        wb = XLSX.read(btoa(o), {  
           //以base64格式讀取
          type: "base64"        
        });
        // 將Excel中的資料賦值給data中的變數(excelInfo)
        this.excelInfo = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
      };
      reader.readAsArrayBuffer(f);
    }
複製程式碼

相關文章