詳解如何實現在Vue中導入Excel文件

以將此Excel導出為json數據為例

一、安裝依賴

npm install file-saver --save
npm install xlsx --save
npm install script-loader --save-dev

二、template中

<span>導入表格</span>
<input id="upload" type="file" @change="importfxx()"  accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />

三、script中js代碼

methods:{
   // 處理導入Excel中日期問題
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1);
      time.setYear(time.getFullYear() - 70);
      const year = time.getFullYear() + "";
      const month = time.getMonth() + 1 + "";
      const date = time.getDate() - 1 + "";
      if (format && format.length === 1) {
        return year + format + month + format + date;
      }
      return (
        year +
        (month < 10 ? "0" + month : month) +
        (date < 10 ? "0" + date : date)
      );
    },

    // 導入Excel
    importfxx() {
      let _this = this;
      let f = event.currentTarget.files[0];
      let rABS = false; //是否將文件讀取為二進制字符串

      let reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function (f) {
        let binary = "";
        let rABS = false; //是否將文件讀取為二進制字符串
        let wb; //讀取完成的數據
        let outdata;
        let reader = new FileReader();
        reader.onload = function (e) {
          let bytes = new Uint8Array(reader.result);
          let length = bytes.byteLength;
          for (let i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          let XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手動轉化
              type: "base64",
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary",
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的東西

          const keyObj = {
            序號: "id",
            情況跟蹤: "track",
            日期: "date",
            標題: "title",
            狀態: "status",
            結果: "result",
            預警: "warning",
          };

          outdata.forEach((item) => {
            // 將中文的鍵名替換成英文的
            for (let k in keyObj) {
              let newKey = keyObj[k];
              if (newKey) {
                item[newKey] = item[k];
                delete item[k];
              }
            }
            item["date"] = _this.formatDate(item["date"], "-");
          });
          console.log(outdata);
        };
        reader.readAsArrayBuffer(f);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
}

如上操作之後,打印結果是如下

到此這篇關於詳解如何實現在Vue中導入Excel文件的文章就介紹到這瞭,更多相關Vue導入Excel文件內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: