前端vue獲取excell中的數據


這個功能我覺得還是挺好的,比如要批量上傳一些數據,然后不用一個一個填入直接寫個excell表然后一起上傳,然后我在這邊記錄一下

首先用到了xlsx這個插件

下載

npm i xlsx --save

使用

在對應的頁面中引入 

import XLSX from "xlsx";
首先上傳文件獲取到文件名,我這邊使用的是element-ui的上傳文件的方法
然后直接上代碼
 // 讀取excell
    importExcel(file) {
      // let file = file.files[0] // 使用傳統的input方法需要加上這一步
      const types = file.name.split(".")[1];
      const fileType = ["xlsx", "xlc", "xlm", "xls", "xlt", "xlw", "csv"].some(
        (item) => item === types
      );
      if (!fileType) {
        this.$message("格式錯誤!請重新選擇");
        return;
      }
      this.file2Xce(file).then((tabJson) => {
        if (tabJson && tabJson.length > 0) {
          this.xlsxJson = tabJson;
          console.log("數據", this.xlsxJson);
          this.excell.tel = [];
          this.excell.name = [];
          this.excell.smstext = [];
          this.xlsxJson[0].sheet.map((item) => {
            // console.log(item,"979887");
            this.excell.name.push(item.name);
            this.excell.tel.push(item.tel);
            this.excell.smstext.push(item.smstext);
          });
          console.log(this.excell, "我的excell");
        }
      });
    },
    file2Xce(file) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader();
        reader.onload = function (e) {
          const data = e.target.result;
          this.wb = XLSX.read(data, {
            type: "binary",
          });
          const result = [];
          this.wb.SheetNames.forEach((sheetName) => {
            result.push({
              sheetName: sheetName,
              sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName]),
            });
          });
          resolve(result);
        };
        reader.readAsBinaryString(file.raw);
        // reader.readAsBinaryString(file) // 傳統input方法
      });
    },

養成把問題記成隨筆的習慣,我覺得是一個非常好的做法

 

 


免責聲明!

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



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