VUE中导入excel文件

40次阅读

共计 2688 个字符,预计需要花费 7 分钟才能阅读完成。

实现的效果如下图

参考文献网址: https://blog.csdn.net/qq_3900…
https://blog.csdn.net/liyi_mo…

安装依赖

npm install xlsx --save

引入

import XLSX from 'xlsx'
Vue.prototype.XLSX = XLSX 

结构

<el-dialog title="入库" class="dialogAdd" width="600px"  :visible.sync="gmDr"  @close="gmDrClose" >
      <el-form :model="gmDrform" :rules="addFormRules" ref="gmDrform" style="margin-right: 20px;" label-position="right" label-width="100px" size="small">
      
        <el-form-item label="入库日期"  prop="storageTime">
          <el-date-picker
            v-model="gmDrform.storageTime"
            type="datetime"
            placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="gmDrTimeChange"
          ></el-date-picker>
        </el-form-item>

            <el-row style="width:100px;padding-right:10px">
                 <el-button  @click="importExcel" size="mini" style="float:right"> 导入 </el-button>
           </el-row> 
          <input type="file" ref="uploadExcel" v-show="false" accept=".xls,.xlsx" @change="readExcel">

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="gmDr = false"> 取 消 </el-button>
        <el-button  size="mini" type="primary" @click="gmDrSure"> 确 定 </el-button>
      </div>
    </el-dialog>
    

data 中的数据

gmDrform:{storageTime:""},// 光猫导入
gmDr:false,
arrList:[],

methods 中

gmDrClick(){ // 获取当前时间, 并赋值给入库日期
    this.gmDr=true
    this.gmDrform.storageTime=this.nowTime()},

  gmDrTimeChange(val){// 入库日期发生变化, 保存到 gmDrform.storageTime 中
    this.gmDrform.storageTime=val
  },

  gmDrClose(){// 关闭模态框, 清除数据
      this.$refs.gmDrform.resetFields();},

importExcel() {
    this.dialogChangePwdVisible = true;
    this.$refs.uploadExcel.click();},
readExcel(e) {
    const files = e.target.files;
    if (files.length <= 0) {
        // 如果没有文件名
        return false;
    }
    const fileReader = new FileReader();
    fileReader.onload = ev => {
      try {
        const data = ev.target.result;
        const workbook = XLSX.read(data, {type: "binary"});
      const wsname = workbook.SheetNames[0]; // 取第一张表
      const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); // 获取到 XLSX 表格中的数据, 并生成 json 格式的数据类型
      // console.log(ws,666);
      let arr = [];
      ws.forEach((value, index, ws) => {
        arr.push({typeNo: ws[index]["光猫型号"] + "",
            boxNo: ws[index]["光猫箱码"] + "",
            snNos: ws[index]["光猫 SN 码"] + "",
            storageTime:this.gmDrform.storageTime+"",
            name:"光猫",
            category:"光猫",
            remarks:"",

        });
      })
      for(let i in arr){let item = arr[i]
          for(let key in item){// console.log(item[key]);
            if(item[key] == "undefined"){delete item[key] 
            }
          }   
          }       
          this.arrList=arr// 给 arrList 赋值, 确定导入时传入
    } catch (e) {return false;}
    };
    fileReader.readAsBinaryString(files[0]);
},

  gmDrSure(){// 确定导入
      let headers={//axios 发送请求时, 需要配置请求头
            headers:{'Accept': 'application/json','Content-Type': 'application/json'}  
            }
      this.startLoading();
      let url = this.config.httpHeadUrl + "/api/modem/admin/saveBatchModem";
      this.$axios.post(url, JSON.stringify(this.arrList),headers ).then(res => {this.$message.success("导入成功!");
      this.gmDr = false;
      this.handleCurrentChange(1);
      this.$refs.uploadExcel.value = "";// 把之前导入的清空
      if(res.data.flag==0){this.$message("导入表头不正确")
        this.gmDr =true
      }
    },(error) => {this.$refs.uploadExcel.value = "";// 把之前导入的清空})
},



正文完
 0