vue +elemenUi+xlsx导入excel表格数据

 <el-button type="info" @click="showExportDialog()">批量发货</el-button>


<el-dialog :visible.sync="isImport" v-if="isImport" :close-on-click-modal="false" :before-close="importDialogHandleClose" title="数据导入" width="30%" v-loading="importButLoading" element-loading-text="正在导入中...">
      <el-form class="edit-form" label-suffix=":" label-width="120px" v-loading="importButLoading" element-loading-text="数据导入中...">
        <el-form-item label="文件导入">
          <el-upload action="/test" ref="import" :on-change="readExcel" :limit="1" :auto-upload="false">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件,且不超过5mb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isImport = false" :disabled="!isImport">取 消</el-button>
        <el-button type="primary" @click="doImport" :loading="importButLoading" :disabled="!isImport">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible="messageDialogVisibel" :close-on-click-modal="false" :before-close="messageDialogHandleClose" title="提示" width="40%">
      <div v-for="(item,index) in messageList1" :key="index">
        <el-alert :closable="false" :center="false" type="warning">
          <template>
            第{{item.index+1}}行
            <template v-for="(l,index) in item.messages" :keys="index">
              {{l.label}} {{l.message}};
            </template>
          </template>
        </el-alert>
        <br>
      </div>
    </el-dialog>
data() {
    return {
      isImport: false,//导入弹窗是否显示
      importData: {},
      tmpData: [],
      messageDialogVisibel: false,
      messageList1: [],
      messageList2: [],
      importButLoading: false,
      regionJson: [],//省市区json
      logisticsList: [],//物流公司 key,value
      updateList: [],//用于记录需要修改的数据
    };
  },
methods:{
     /*
    * 批量发货: 
    * 1:检查是否存在已经发货的了订单,
    * 2:向运单表中添加数据:(1):匹配 物流公司编码,(2):匹配收货人行政区域编码
    * 3:修改订单item表中的运单编号:根据订单编号和商品编号,商品规格编号匹配 订单item表中的 id
    * 4:修改订单状态为已发货。
    */
    addBatch(params) {
      var me = this;

      this.$dyform.dispose('logistics-waybill', "exportData", params)
        .then(res => {
          if (res.data.success) {
            for (let i = 0; i < this.updateList.length; i++) {
              me.updateWaybillCode(this.updateList[i])
            }
            setTimeout(() => {
              me.$message({
                type: "success",
                dangerouslyUseHTMLString: true,
                message: "数据导入成功",
              });
              //需要定时执行的代码
              me.isImport = false;
              me.importButLoading = false;
              me.loadData();
            }, 5000)

          } else {
            me.importButLoading = false;
            me.messageDialogVisibel = true;
            if (!res.data.success) {
              res.data.messageList.forEach((item) => {
                me.messageList1 = res.data.messageList;
              });
            }
            if (!res.data.success) {
              me.messageList2 = res.data.messageList;

            }
          }
        })
        .catch(function (error) {
          me.isImport = false;
          me.importButLoading = false;
          me.$message.error("操作失败,请联系管理员!");
        });

    },
    //验证数据的合法性
    checkDatas(list) {
      var me = this;
      let data = []
      //处理数据前,先给导入信息去重复,根据运单号和订单号
      var flag = true
      for (let i = 0; i < list.length; i++) {
        let map = {
          orderCode: list[i]["订单号"],
          goodsCode: list[i]["商品编号"],
          infoCode: list[i]["商品规格编号"],
          waybillCode: list[i]["运单号"],
          quantity: list[i]["发货数量"]
        }
        this.updateList.push(map)
        if (list[i]["订单号"] == "" || list[i]["订单号"] == null) {
          me.$message.error("第" + (i + 1) + "行,订单号不能为空");
          me.isImport = false;
          me.importButLoading = false
          return false
        }
        //运单号判空
        if (list[i]["运单号"] == "" || list[i]["运单号"] == null) {
          me.$message.error("第" + (i + 1) + "行,运单号不能为空");
          me.isImport = false;
          me.importButLoading = false
          return false
        }
        //商品编号判空
        if (list[i]["商品编号"] == "" || list[i]["商品编号"] == null) {
          me.$message.error("第" + (i + 1) + "行,商品编号不能为空");
          me.isImport = false;
          me.importButLoading = false
          return false
        }
        //发货数量判空
        if (list[i]["发货数量"] == "" || list[i]["发货数量"] == null) {
          me.$message.error("第" + (i + 1) + "行,发货数量不能为空");
          me.isImport = false;
          me.importButLoading = false
          return false
        }
        //商品规格编号判空
        if (list[i]["商品规格编号"] == "" || list[i]["商品规格编号"] == null) {
          me.$message.error("第" + (i + 1) + "行,商品规格编号不能为空");
          me.isImport = false;
          me.importButLoading = false
          return false
        }
        //物流公司判空
        if (list[i]["物流公司"] == "" || list[i]["物流公司"] == null) {
          me.$message.error("第" + (i + 1) + "行,物流公司不能为空");
          me.isImport = false;
          me.importButLoading = false
          return false
        }
        flag = true
        for (let j = 0; j < data.length; j++) {
          if (list[i]["订单号"] == data[j]["订单号"] && list[i]["运单号"] == data[j]["运单号"]) {
            flag = false
          }
        }
        if (flag) {
          data.push(list[i])
        }
      }
      for (var i = 0; i < data.length; i++) {
        me.importData["id"].push("");
        me.importData["waybillCode"].push(
          data[i]["运单号"] ? data[i]["运单号"] : ""
        );
        me.importData["orderCode"].push(
          data[i]["订单号"] ? data[i]["订单号"] : ""
        );
        me.importData["postalCode"].push(
          data[i]["邮政编码"] ? data[i]["邮政编码"] : ""
        );
        me.importData["consignee"].push(
          data[i]["用户名"] ? data[i]["用户名"] : ""
        );
        me.importData["consigneeTel"].push(
          data[i]["联系方式"] ? data[i]["联系方式"] : ""
        );
        me.importData["consigneeRegion"].push(
          data[i]["收货人行政区域"] ? data[i]["收货人行政区域"] : ""
        );

        let codeMap = this.logisticsList.find(item => item.expressCompany == data[i]["物流公司"])
        me.importData["logisticsCode"].push(
          codeMap ? codeMap.code : ""
        );
        let regionCode = ""//省市区编码
        if (data[i]["收货人行政区域"]) {
          let region = data[i]["收货人行政区域"].split('/')
          if (region.length == 3) {
            //匹配省
            let regionChildren = [] //市
            for (let i = 0; i < this.regionJson.length; i++) {
              if (this.regionJson[i].name == region[0]) {
                regionChildren = this.regionJson[i].children
                regionCode += this.regionJson[i].code
              }
            }
            //匹配市
            let regionChildren1 = []//区
            for (let i = 0; i < regionChildren.length; i++) {
              console.log(regionChildren[i].name);
              if (regionChildren[i].name === region[1]) {
                regionChildren1 = regionChildren[i].children
                regionCode += '-' + regionChildren[i].code
              }
            }
            //匹配区
            for (let i = 0; i < regionChildren1.length; i++) {
              if (regionChildren1[i].name === region[2]) {
                regionCode += '-' + regionChildren1[i].code
              }
            }
          } else {
            me.$message.error("第" + (i + 1) + "行,行政区域格式错误,例:北京市/市辖区/和平区");
            me.isImport = false;
            me.importButLoading = false
            return false
          }
        }
        // //省市区编码!
        me.importData["consigneeCode"].push(regionCode);
        me.importData["consigneeAddr"].push(
          data[i]["收货地址"] ? data[i]["收货地址"] : ""
        );
        me.importData["sender"].push(
          data[i]["寄件人"] ? data[i]["寄件人"] : ""
        );
        me.importData["senderAddr"].push(
          data[i]["寄件人地址"] ? data[i]["寄件人地址"] : ""
        );
        me.importData["senderTel"].push(
          data[i]["寄件人电话"] ? data[i]["寄件人电话"] : ""
        );

      }
      me.addBatch(me.importData);
    },

    //初始化数据
    initImportData() {
      this.importData["id"] = []; //物流表订单id
      this.importData["waybillCode"] = [];//运单编号
      this.importData["orderCode"] = [];//订单号
      this.importData["logisticsCode"] = [];//物流公司编码
      this.importData["postalCode"] = [];//邮政编码
      this.importData["consignee"] = [];//收货人
      this.importData["consigneeTel"] = [];//收货人手机号
      this.importData["consigneeRegion"] = [];//收货人所在行政区域
      this.importData["consigneeCode"] = [];//收货人行政区域编码
      this.importData["consigneeAddr"] = [];//收货人详细地址
      this.importData["sender"] = [];//寄件人
      this.importData["senderAddr"] = [];//寄件地址
      this.importData["senderTel"] = [];//寄件人手机号
      this.importData["remark"] = [];
    },

doImport() {
      if (this.$refs.import.uploadFiles.length > 0) {
        if (this.tmpData && this.tmpData.length > 0) {
          this.importButLoading = true;
          //this.isImport = false
          //初始化导入所需数据
          this.initImportData();
          //验证数据合法性
          this.checkDatas(this.tmpData);
        } else {
          this.$message.warning("文件类型不正确!只支持excel格式(xls,xlsx)");
        }
      } else {
        this.$message.warning("请先上传文件!");
      }
    },

 //点击批量导入时
    showExportDialog() {
      //查询物流公司名字编码,用于匹配
      // this.getNameCode()
      this.isImport = true
      this.getNameCode()
    },
    readExcel(file) {
      var me = this;
      if (this.beforeImport(file)) {
        this.$readExcel(file, 1)
          .then(function (data) {
            me.tmpData = data;
            // me.parseImportData(data)
          })
          .catch(function () {
            me.$message.error("文件类型不正确!");
          });
      }
    },
    beforeImport(file) {
      var ext = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension = ext === "xls";
      const extension2 = ext === "xlsx";
      const isImg = extension || extension2;
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isImg) {
        this.$message.error("上传文件只能是 xls、xlsx格式!");
      }
      if (!isLt2M) {
        this.$message.error("导入文件大小不能超过 5MB!");
      }
      return isImg && isLt2M;
    },

 //关闭导入错误信息弹窗
    messageDialogHandleClose() {
      this.tmpData = []
      this.messageDialogVisibel = false;
    },
    //关闭导入弹窗
    importDialogHandleClose() {
      this.isImport = false;

    },

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于 Vue 和 Element UI 的导入 Excel 的示例代码: ```vue <template> <div> <el-upload class="upload-excel" :before-upload="beforeUpload" :on-success="onUploadSuccess" :on-error="onUploadError" :file-list="fileList" :accept=".xlsx,.xls" :auto-upload="false" > <el-button slot="trigger" type="primary">选择文件</el-button> <el-button slot="append" type="success" :disabled="!fileList.length" @click="uploadExcel">上传</el-button> <div slot="tip" class="el-upload__tip">只能上传 .xlsx 或 .xls 文件</div> </el-upload> </div> </template> <script> import XLSX from 'xlsx' export default { data() { return { fileList: [] } }, methods: { beforeUpload(file) { // 校验文件类型 const isXLS = file.type === 'application/vnd.ms-excel' const isXLSX = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' const isExcel = isXLS || isXLSX if (!isExcel) { this.$message.error('只能上传 .xlsx 或 .xls 文件') return false } // 添加到 fileList 中 this.fileList.push(file) return false // 阻止自动上传 }, onUploadSuccess(response) { // 上传成功后的处理逻辑 this.$message.success('上传成功!') }, onUploadError(error) { // 上传失败后的处理逻辑 this.$message.error('上传失败!') }, uploadExcel() { // 读取 Excel 文件内容,此处使用了 xlsx 库 const file = this.fileList[0] const reader = new FileReader() reader.onload = (e) => { const data = e.target.result const workbook = XLSX.read(data, { type: 'binary' }) const sheetName = workbook.SheetNames[0] const worksheet = workbook.Sheets[sheetName] const json = XLSX.utils.sheet_to_json(worksheet) console.log(json) // 打印 Excel 数据 } reader.readAsBinaryString(file.raw) } } } </script> ``` 解释一下: 1. 组件中包含一个 `el-upload` 组件,用于上传 Excel 文件。 2. `beforeUpload` 方法用于校验文件类型,并将文件添加到 `fileList` 中。 3. `onUploadSuccess` 和 `onUploadError` 分别是上传成功和上传失败的回调函数。 4. `uploadExcel` 方法用于读取 Excel 文件内容,使用了 `xlsx` 库将 Excel 数据转换成 JSON 数据

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值