Element ui 实现导入excel表格功能

989 阅读1分钟

使用element ui的el-upload来实现导入excel表格功能

HTML
<el-upload
              class="upload-demo"
              action="string"
              accept=".xlsx,.xls"
              :on-success="handsuccess"
              :before-upload="handbeforeupload"
              :http-request="httpRequest"
            >
              <el-button size="small" type="danger" plain>导入</el-button>
</el-upload>

methods

 // 导入之前的钩子
    handbeforeupload(file) {
      this.fileName = file.name;
      const isExcel =
        file.name.split(".")[1] === "xlsx" || file.name.split(".")[1] === "xls";
      const isSize = file.size / 1024 / 1024 < 10;
      if (!isExcel) {
        this.$message({
          message: "只能上传xls或xlsx文件!",
          type: "warning",
          showClose: true,
        });
      }
      if (!isSize) {
        this.$message({
          message: "上传文件大小不能超过 10MB!",
          type: "warning",
          showClose: true,
        });
      }
      return isExcel && isSize;
    },
    
   // 导入
    httpRequest(params) {
      let fd = new FormData();
      fd.append("file", params.file);
      importExcelApi(fd)
        .then((res) => {
          if (res.resultCode == 0) {
            this.resultMsgVal = res.resultMsg;
            this.getDataList();
            this.$message({
              message: "上传成功",
              type: "success",
              showClose: true,
            });
          } else if (res.resultCode == 500) {
            this.$message({
              message: res.resultMsg,
              type: "warning",
              showClose: true,
            });
          } else if (res.resultCode == 40001) {
            this.$message({
              message: res.resultMsg,
              type: "warning",
              showClose: true,
            });
          }
        })
        .catch((err) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
          // this.$message({ message: err, type: "warning", showClose: true });
        });
    },

    handsuccess() {
      // console.log("导入成功");
    },