xlsx 解析excel 文件

75 阅读1分钟
import * as xlsx from "COMMON_NODE_MODULES/xlsx";

headers: [],
data: [],


//上传的excel
beforeUpload(file) {
  const isExcel =
    file.type ===
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
    file.type === "application/vnd.ms-excel";
  console.log(isExcel, "isExcel");
  if (!isExcel) {
    this.$Message.warning("只能上传 .xlsx 或者.xls 格式的文件");
    return false;
  }
  // 重置文件列表
  this.fileList = file; 
  const reader = new FileReader(); 
  reader.onload = (e) => {
    console.log(e, "load");
    const data = new Uint8Array(e.target.result);
    const workbook = xlsx.read(data, { type: "array" });
    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];
    const json = xlsx.utils.sheet_to_json(worksheet, { header: 1 }); 
    // 解析表头 
    // this.headers = json[0]; 
    // 解析数据行
    this.data = json.slice(1);
    console.log(this.data, "333333333"); 
  };
  reader.readAsArrayBuffer(file); // 确保调用此方法以启动文件读取 ,必须
  return false;
},
 

//拿到excel  内容 遍历上传

confirm() {
  if (!this.fileList) {
    this.$message.error("请上传文件");
    return;
  }
  console.log(this.data, "this.data");

  // 创建一个Promise数组,每个Promise对应一个data项的处理
  const promises = this.data.map((item) => {
    return this.getAdd(item).then(() => {});
  });

  // 使用Promise.all等待所有异步操作完成
  Promise.all(promises)
    .then(() => {
      // 所有异步操作完成后,调用this.$emit("importResh")
      this.loading = false;
      this.$Message.success("导入成功");
      this.cancel();
      this.$emit("importResh");
    })
    .catch((error) => {
      console.error("Error processing items:", error);
      // 如果有任何错误发生,你可能也想在这里处理或通知用户
    });
},