天天看點

Vue cli3 讀取xlsx

1.npm 安裝xlsx

npm i xlsx
           

2.建立一個ts檔案 并加上以下代碼

import XLSX from 'xlsx'
function xlsxTool(file: any) {
    return new Promise((fn: (r: object) => void, error: () => void) => {
        var reader = new FileReader();
        reader.onload = function (e: any) {
            try {
                var data = e.target.result;
                var workbook = XLSX.read(data, { type: 'binary' });
                //console.log(workbook);

                var datas = workbook.Sheets[workbook.SheetNames[0]];
                //console.log(datas);

                var allColumn = [];
                for (var i = 0; i < 26; i++) {
                    allColumn.push(String.fromCharCode((65 + i)));
                }

                var hread: any = [];
                var column: any = [];
                allColumn.forEach(d => {
                    if (datas[`${d}1`] != null) {
                        hread.push(datas[`${d}1`].v);
                        column.push(d);
                    }
                })

                var objs = [];
                for (var i = 2; i <= 100; i++) {
                    if (datas[`A${i}`] == null) {
                        break;
                    }
                    var obj = {};
                    column.forEach((d: any, ii: number) => {
                        (obj as any)[`${hread[ii]}`] = datas[`${d}${i}`] == null ? "" : datas[`${d}${i}`].v;
                    })
                    objs.push(obj);
                }
                //console.log(objs);
                fn(objs);
            }
            catch (errorMsg) {
                error();
            }
        };
        reader.readAsBinaryString(file);
    })
}


export default xlsxTool
           

3.在要使用的頁面導入上面的ts檔案

import xlsx from "../../api/exam/xlsx";
           

4.定義file隐藏域

<input type="file" hidden id="qb_file" @change="table.fileChange" />
           

5.點選按鈕時觸發file點選事件

//打開檔案選擇
      openFile: () => {
        let qb_file: any | null = document.getElementById("qb_file");
        qb_file.value = null; //清空上次選擇的檔案
        qb_file.click();
      },
           

6.file發生更改時觸發的事件

//當檔案改變時
      fileChange: () => {
        let qb_file: any | null = document.getElementById("qb_file");
        const fileName = qb_file.value;
        if (fileName != undefined && fileName != null && fileName != "") {
          const fileExtension = fileName.substring(
            fileName.lastIndexOf(".") + 1
          );
          if (fileExtension == "xlsx") {
            console.log(qb_file.files[0]);
            xlsx(qb_file.files[0]).then((r: any) => {
              var questions: any = []; //臨時存放questions對象的集合
              r.forEach((item: any) => {
                questions.push({
                  //将導出的資料裝入臨時集合
                  topicDry: item.題幹,
                  topic: item.題型,
                  options: item.選項.split("|,|"),
                  lv: item.難度,
                  type: item.類型,
                });
              });
              testQuestions.questions = questions; //将臨時集合的資料給真正的集合
            });
          } else {
            //選擇的不是xlsx檔案
            ElNotification({
              title: "錯誤",
              message: "請選擇正确檔案",
              type: "error",
            });
          }
        } else {
          //沒有選擇檔案
          ElNotification({
            title: "錯誤",
            message: "請選擇檔案再操作",
            type: "error",
          });
        }
      },
           

結果:

Vue cli3 讀取xlsx

繼續閱讀