vue解析上传的excel文档

template中的内容

    <a-upload
      name="file"
      :multiple="true"
      :beforeUpload="beforeUpload"
      accept=".xlsx, .xls"
      @change="handleChange"
    >
      <a-button> <a-icon type="upload" /> 点击上传 </a-button>
    </a-upload>

methods代码

// 修改上传的状态
  beforeUpload (file) {
    file.status = 'uploading'
    return false
  },
 //  移除一个上传的文件
 handleRemove (file) {
    const index = this.fileList.indexOf(file)
     this.fileList.splice(index, 1)
   },
   // 上传完成之后的文件处理
    handleChange (info) {
      console.log('info', info)
      const { file, fileList } = info
      if (file.status === 'removed') {
        this.handleRemove(file)
      } else {
        this.fileList = fileList
        let index
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].uid === file.uid) {
            index = i
            break
          }
        }
        this.handleUpload(file, index)
      }
    },
    // 上传完成之后处理文件
    handleUpload (file, index) {
      this.handleReadExcel(file)
      this.fileList[index].status = 'done'
    },   
    // (重点)把文件按照二进制读取
    handleReadExcel (file) {
      const that = this
      const fileReader = new FileReader()
      fileReader.onload = ev => {
        try {
          const fileData = ev.target.result
          const workbook = XLSX.read(fileData, {
            type: 'binary'
          })
          const wsname = workbook.SheetNames[0] // 取第一张表
          const snArr = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) // 生成json表格内容
          // console.log(snArr) // 读取到的SN列表
          // 遍历SN放入Set集合 snSet
          that.dataGrid.snSet.clear() // 清空一下之前的Set
          snArr.forEach(item => {
            that.dataGrid.snSet.add(item.sn)
          })
          console.log(that.dataGrid.snSet)
          // 处理完SN列表之后可以开放OK按钮
          this.enableSubmit = false
        } catch (e) {
          return false
        }
      }
      fileReader.readAsBinaryString(file)
    },

最后提示一点不要忘了引入解析xlsl的包,需要下载再引入

import XLSX from 'xlsx'
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值