vue+element-ui+xlsx讀取excel表數據

先安裝 xlsx

npm i xlsx --save

然後再文件引入

import XLSX from “xlsx”;

然後封裝一個讀取xlsx的函數 你可以放到你常用的utils.js文件裏面 或者就寫在當前vue文件都可以

function readXLSX(file) {
  let nameSplit = file.name.split(".");
  let format = nameSplit[nameSplit.length - 1];
  if (!["xlsx", "csv"].includes(format)) {
    return false;
  }
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = evt => {
      let data = evt.target.result; // 讀到的數據
      let workbook = XLSX.read(data, { type: "binary" });
      resolve(workbook);
    };
  });
}

先上個vue上傳文件的組件代碼

 <el-upload
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :before-upload="beforeUpload"
            ></el-upload>

觸發下面函數

  async beforeUpload(file) {
      let result = await readXLSX(file);  //讀取到的內容
      console.log(result)  //此處爲xlsx文件內容 
  }

有什麼不懂的可以留言

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章