JS之實現Excel資料匯入

罗毅豪發表於2024-09-04

1.<template>部分

<a-upload
  name="file"
  :customRequest="importExcelData"
  accept=".xls,.xlsx"
  class="uploadBtn"
  :showUploadList="false"
>
  <a-button
    type="primary"
    style="margin-right: 8px"
    :loading="uploading"
    >匯入excel</a-button
  >
</a-upload>

2.匯入xlsx

import * as xlsx from "xlsx";

3.<script>部分

//匯入excel
const uploading = ref(false);
// 檔案上傳自定義
const importExcelData = async (op) => {
  uploading.value = true;

  // 獲取上傳的excel  並解析資料
  let file = op.file;
  let dataBinary = await readFile(file);
  let workBook = xlsx.read(dataBinary, { type: "binary", cellDates: true });

  let workSheet = workBook.Sheets[workBook.SheetNames[0]];
  const excelData = xlsx.utils.sheet_to_json(workSheet);

  let result = [];
  for (let i = 0; i < excelData.length; i++) {
    //迴圈excel資料,將欄位名置為英文字元,值為當前項相應表頭欄位的值,拼成介面需要的資料格式
    // 定義要匯出的
    let sheetData = {
      branch: excelData[i]["分公司"], //第i項,對應表頭為樓宇名稱的列值
      grid: excelData[i]["網格"],
      buildingId: excelData[i]["樓宇id"],
      buildingName: excelData[i]["樓宇名稱"],
    };
    result.push(sheetData);
  }
  return new Promise((resolve, reject) => {
    GzBuildingsApi.importExcelData(result)
      .then((response) => {
        const data = response.data;
        if (data.code === 200) {
          message.success("匯入成功");
          uploading.value = false;
          query();
        } else {
          message.error(data.message);
        }
      })
      .catch((error) => {});
  });
};

const readFile = (file) => {
  return new Promise((resolve) => {
    let reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = (ev) => {
      resolve(ev.target?.result);
    };
  });
};

相關文章