VUE中導入excel文件

實現的效果以下圖
圖片描述ios

參考文獻網址: https://blog.csdn.net/qq_3900...
https://blog.csdn.net/liyi_mo...npm

安裝依賴json

npm install xlsx --save

引入axios

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

結構api

<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中的數據app

gmDrform:{storageTime:""},//光貓導入
gmDr:false,
arrList:[],

methods中post

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 = "";//把以前導入的清空
    })
},
相關文章
相關標籤/搜索