【拿来即用】前端实现上传excel文件功能,并处理好数据传给后端

上传excel功能并前端解析成数据传给后端

在这里插入图片描述

需要用到xlsx

cnpm install xlsx --save

组件内注册一下

import XLSX from "xlsx";

结构部分

直接复制

      <el-form-item>
        <el-upload
          class="upload-demo"
          ref="upload"
          action="#"
          :http-request="importFile"
          :before-upload="beforeAvatarUpload"
          :auto-upload="false"
          :limit="1"
          accept=".xls,.xlsx,.csv"
          :on-exceed="handleExceed"
        >
          <el-button slot="trigger" type="primary" size="small"
            >选取文件</el-button
          >
          <el-button
            :loading="dataForms.loading"
            style="margin-left: 10px"
            type="success"
            @click="fileSubmit"
            size="small"
            v-loading.fullscreen.lock="fullscreenLoading"
            element-loading-text="正在执行..."
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.8)"
            >上传</el-button
          >
          <!-- <div slot="tip" class="el-upload__tip">只能上传Excel文件</div> -->
          <el-button type="primary" @click="cancleUpload" size="small"
            >取消</el-button
          >
        </el-upload>
      </el-form-item>

data部分

直接复制

  data() {
    return {
      dataForms: {
        barCode: "",
        loading: false,
      },
      fullscreenLoading: false, // 加载中
      desc: "",
      loadingText: "正在执行...",
    };
  },

methods部分

复制就行

    fileSubmit() {
      //没有选取文件弹出提醒
      if (this.$refs.upload.uploadFiles.length < 1) {
        this.$message.warning("请先选择一个文件");
      } else {
        //否则提交
        this.$refs.upload.submit();
      }
    },
    //上传文件前的钩子,file是文件
    beforeAvatarUpload(file) {
      //拿到文件大小是否小于10
      const isLt10M = file.size / 1024 / 1024 < 10;
      //不小于10提醒过大
      if (!isLt10M) {
        this.$message.error("上传文件大小不能超过 10MB!");
      } else {
        //否则加载效果出现
        this.fullscreenLoading = true;
      }
      return isLt10M;
    },
    //限制选择文件数量一个
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件,请先删除下方文件,重新选择`);
    },
    //取消上传请求,abord是el-Upload的自带取消上传请求的方法
    cancleUpload() {
      this.$refs.upload.abord();
    },
    //http-request:覆盖默认的上传行为
    importFile(files) {
      //loading图显示正在解析
      this.loadingText = "正在解析";
      //
      var fileReader = new FileReader();
      //加载图显示
      this.dataForms.loading = true;
      // 以二进制方式打开文件
      fileReader.readAsBinaryString(files.file);
      fileReader.onload = (ev) => {
        try {
          var data = ev.target.result,
            workbook = XLSX.read(data, {
              type: "binary",
            }), // 以二进制流方式读取得到整份excel表格对象
            persons = [];
        } catch (e) {
          this.$message.error("文件类型不正确");
          this.dataForm.loading = false;
          this.imFile = null;
          this.$refs.upload.clearFiles();
          this.fullscreenLoading = false;
          return;
        }
        // 表格的表格范围,可用于判断表头是否数量是否正确
        var fromTo = "";
        // 遍历每张表读取
        for (var sheet in workbook.Sheets) {
          if (workbook.Sheets.hasOwnProperty(sheet)) {
            fromTo = workbook.Sheets[sheet]["!ref"];
            //这是处理好的数据
            persons = persons.concat(
              XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
            );
            break; // 如果只取第一张表,就取消注释这行
          }
        }
        this.loadingText = "正在上传...";
        //请求后台
        this.$http({
          url: this.$http.adornUrl("/ExcelExport/codeInfoImport"),
          method: "POST",
          data: this.$http.adornData({
            inputData: persons,
            desc: this.desc,
          }),
          .then(({ data }) => {
            if (data && data.code === 0) {
              this.loadingText = "";
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
              });
              this.dataForm.loading = false;
              this.getDataList();
              this.$refs.upload.clearFiles();
              this.imFile = null;
              this.desc = "";
              this.fullscreenLoading = false;
            } else {
              this.$message.error(data.msg);
              this.$refs.upload.clearFiles();
              this.dataForm.loading = false;
              this.fullscreenLoading = false;
            }
          })
          .catch((error) => {
            this.$message.error(error.toString());
            this.$refs.upload.clearFiles();
            this.dataForm.loading = false;
            this.fullscreenLoading = false;
          });
      };
    },

解析后拿到传给后台的数据是这样的

在这里插入图片描述
就成了数组套对象的模式,把表格传给了后台,后台直接用就行了。

  • 9
    点赞
  • 65
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

接口写好了吗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值