VUE-elementui下利用inputfile读取excel,inputfile样式修改

1.为什么用inputfile不用elementui原生upload?

el-upload试过必须填action地址给我整不会了。

2.为什么添加一个按钮触发inputfile事件?

原生的inputfile太丑了,看不下去。

3.我要实现什么

实现读取excel中数据转换为对应数据

导入xlsx

npm install xlsx -S

创建组件excelReader

<template>
  <div>
    <el-button style="height: 30px; margin: 5px 0 0 10px;" size="mini" @click="triggerUpload">上传文件</el-button>
    <input
      v-show="false"
      ref="fileTemp"
      type="file"
      accept=".xlsx,.xls"
      @change="getImportFile"
    />
  </div>
</template>

<script>
  import XLSX from 'xlsx' 

  export default {
    data () {
      return {
        names: [],
      }
    },
    methods: {
      // 用按钮触发input上传空间
      triggerUpload () {
        this.$refs.fileTemp.click()
      },
      // 获取文件
      getImportFile () {
        if (this.$refs.fileTemp && !this.$refs.fileTemp.files[0]) return false
        const selectedFile = this.$refs.fileTemp.files[0]
        this.readFile(selectedFile)
      },
      // 将文件转换成 JSON
      readFile (file) {
        const that = this
        const reader = new FileReader()
        reader.onload = function (e) {
          const wb = XLSX.read(e.target.result, { type: 'binary' }) // 读取文件
          const wbSheetName = wb.SheetNames[0]
          const wbSheet = wb.Sheets[wbSheetName]
          // 解析文件 {defval: ''}=>防止单元格为空的时解析出来的结果缺少相应的key
          const selectFileData = XLSX.utils.sheet_to_json(wbSheet, { defval: '' })
          if (!selectFileData.length) {
            that.$message.warning(`上传的文件数据为空!`)
            return false
          } else {
            that.$message.success(`读取文件成功!`)
          }
          // 对获取到的对象数组进行操作
          for (let i = 0; i < selectFileData.length; i++) {
            delete selectFileData[i].__EMPTY
          }
          // 将对象数组 转换成 JSON类型,这一块我只选了名称,各位自行筛选
          const names = []
          for (const data of selectFileData) {
            names.push(data['名称'])
          }
          that.$emit('transName2Ids', names)
        }
        reader.readAsBinaryString(file)
      },
    },
  }
</script>

<style scoped>

</style>

父组件引入,其中transName2Ids是父组件处理数据的方法

<excel-read @transName2Ids="transName2Ids"></excel-read>

实现效果

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值