Element UI+VUE Excel导入

导入代码如下(自用)

这个个人在做的时候也对照了一些百度给的例子 万变不离其宗主要感觉还是需要把Excel要上传的模板写好 其他的就都没有问题了~

<template>
  <!--列表-->
  <el-dialog v-loading="excelLoading" title='特种信息导入' :visible.sync="dialogVisible"  width="40%">
    <div style="margin-left:20px">
      <el-form
              ref="detailsForm"
              :inline="true" 
              :rules="rules"   
              :model ="detailsForm"
            >
          <!--工程项目-->
           <el-row>  
               <el-form-item label="工程项目" prop="ProjectId" >
                 <el-select v-model="detailsForm.ProjectId" placeholder="请选择工程项目" >
                 <el-option  v-for="item in ProjectNameOptions"  :key="item.DicItem" :label="item.DicValue" :value="item.DicItem" />
                 </el-select>
               </el-form-item>
           </el-row>
      </el-form>
      <el-upload
        class="upload-demo"
        :action="fileUploadAction"
        :on-change="handleChange"
        :on-remove="handleRemove"
        :on-exceed="handleExceed"
        accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
        :auto-upload="false"
      >
        <el-button type="primary" style="color: #33ffdd">{{ $t("Button.SelectImportFile") }}</el-button><!--选择导入文件-->
        </el-upload>  
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="importExcel(null)">{{ $t('Button.Cancel') }}</el-button>   <!--取消-->
      <el-button type="primary" @click="importExcelAdd">{{ $t('Button.Confirm') }}</el-button>  <!--确定-->
    </span>
  </el-dialog>
</template>

<script>
import { SpecialEquipmentImportExcel,getProjectSelectList } from '../api/ys-api'
import enums from '../../common/enums'
import { isNullOfValue } from '../../common/common'

export default {
  name: 'ImportExcel',
  data() {
    return {
      fileUploadAction: enums.fileUploadUrl + enums.ModuleName.YS, // 附件上传API
      userInfo: null, // 用户信息
      dialogVisible: true, // 控制是否显示等待画面
      fileEvent: null,  //文件事件
      rowData: null,  //行数据
      excelLoading: false,  //EXCEL加载
      ProjectNameOptions: [], // 工程项目名称
      detailsForm: { ProjectId: undefined,   }, //项目Id
      flag: false,

    //工程名称
    rules:{
      ProjectId:[{required:true,message:'请选择工程项目名称',trigger:'change'}] 
    },
   }
  },

  created() {
    // 获取用户信息
    this.userInfo = JSON.parse(localStorage.getItem('userInfo'))
    this.systemConfigType = enums.SystemConfigType
     getProjectSelectList('').then((res) => {
        this.ProjectNameOptions = res.response
      }) 

  },

  methods: {
    // 上传文件时处理方法
    importExcel(row) {
      this.dialogVisible = false
    },
     init(row,flag) {
      this.dialogVisible = true
      this.rowData = row
      this.flag = flag
    },
    //初始化
    //处理变更
    handleChange(file, fileList) {
      this.fileTemp = file.raw
      if (this.fileTemp) {
        if ((this.fileTemp.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
                || (this.fileTemp.type == 'application/vnd.ms-excel')) {
          // excel 导入节点
          this.fileEvent = event.currentTarget.files[0]
        } else {
          this.$message({
            type: 'warning',
            message: this.$t('Message.W00108') //附件格式错误,请删除后重新上传!
          })
        }
      } else {
        this.$message({
          type: 'warning',
          message: this.$t('Message.W00109')  //请上传附件!
        })
      }
    },

    // 超出最大上传文件数量时的处理方法
    handleExceed() {
      this.$message({
        type: 'warning',
        message: this.$t('Message.W00107')  //上传文件大小不能超过 5MB
      })
      return
    },

    // 移除文件的操作方法
    handleRemove(file, fileList) {
      this.fileTemp = null
    },

    //导入Excel添加
    importExcelAdd(obj) {
  
      this.excelLoading = true
      let _this = this
      // 通过DOM取文件数据
      if (isNullOfValue(_this.fileEvent)) {
        _this.$notify({
          title: _this.$t('Title.Warning'),
          message: _this.$t('Message.W00116'),  //请使用系统提供的(人员信息导入模版)进行导入!
          type: 'warning',
          duration: 3000
        })
        this.excelLoading = false
        return
      }
      this.file = _this.fileEvent
      var rABS = false // 是否将文件读取为二进制字符串
      var f = this.file
      var reader = new FileReader()
      FileReader.prototype.readAsBinaryString = function(f) {
        var binary = ''
        var rABS = false // 是否将文件读取为二进制字符串
        var pt = this
        var wb // 读取完成的数据
        var outdata
        var reader = new FileReader()
        reader.onload = function(e) {
          var bytes = new Uint8Array(reader.result)
          var length = bytes.byteLength
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i])
          }
          // 此处引入,用于解析excel
          var XLSX = require('xlsx')
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              // 手动转化
              type: 'base64',
              cellDates: true
            })
          } else {
            wb = XLSX.read(binary, {
              type: 'binary',
              cellDates: true
            })
          }
          //判定模板
          if ((wb.SheetNames[0] !== '特种设备信息' || wb.SheetNames[2] !== 'Sheet1')) {
            _this.excelLoading = false
            _this.$notify({
              title: _this.$t('Title.Warning'),
              message: _this.$t('Message.W00116'), //请使用系统提供的(人员信息导入模版)进行导入
              type: 'warning',
              duration: 3000
            })
            return
          }
         
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[2]])
          // outdata就是读取的数据(不包含标题行即表头,表头会作为对象的下标)
          // 特种设备信息
            let arr = []
          outdata.map(v => {
            let obj = {}
            debugger
            obj.ProjectId = _this.detailsForm.ProjectId //获取导入的工程名称下拉值
            obj.SpecialEquipmentCode = v['特种设备代码']
            obj.SpecialEquipmentName = v['特种设备名称']
            obj.EndDate = v['合格证失效日期']
            obj.SpecialEquipmentCardCate = v['特种设备证件名称']
            obj.SpecialEquipmentType = v['特种设备种类']
            obj.SpecialEquipmentCate = v['特种设备类别']
            obj.SpecialEquipmentVariety = v['特种设备品种']
            obj.ConstructionUnit = v['建设单位']
            obj.UseUnit = v['使用单位']
            obj.SpecialEqPerLiable = v['特种设备责任人']
            obj.UseArea = v['使用区域']
            obj.Rummager = v['检查人']
            obj.Updater = _this.userInfo.userId
            obj.UpdaterName = _this.userInfo.userName
            obj.UpdateTime = _this.fmtDataTime(new Date())
            obj.Creator = _this.userInfo.userId
            obj.CreatorName = _this.userInfo.userName
            obj.CreateTime = _this.fmtDataTime(new Date())
            obj.AffiliatedUnitsCode = _this.userInfo.OrgId
            obj.AffiliatedUnitsNm = _this.userInfo.orgName

            arr.push(obj)
          })

          console.log(arr);
          SpecialEquipmentImportExcel(arr).then((res) => {

            _this.$emit('importSpEq',false);
            //this.dialogFormModelVisible = false;
          })
        }
        reader.readAsArrayBuffer(f);
      }
        if(rABS){
          reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
  }
}
</script>

<style scoped>
  .page-container {
    margin: 10px 10px 10px;
    background: #fff;
    position: relative;
  }

  .table-head-dropdown {
    position: absolute;
    left: 5px;
    top: 10px;
    z-index: 100;
  }
</style>

是单独写的有个vue然后在页面上调用这个页面

模板里是需要去找到key值 要取得是字典组得英文名 而不是手敲上就可以!

基本代码如上,细节未写可以正常上传出结果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值