vue antd前端js获取导入excel xls数据

第一步:npm insyall xlsx

<template>
  <div class="upload-content">
    <a-upload
      accept=".xls,.xlsx"
      :showUploadList="false"
      action=""
      name="file"
      @change="exportData"
    >
      <a-button type="primary"> <a-icon type="upload" /> 点击上传 </a-button>
    </a-upload>
    <div class="list-box" v-if="valueList.length > 0">
      <span class="step-title">搜索字段:</span>
      <span v-for="(i, index) in valueList" :key="index">{{ i }},</span>
    </div>
    <ul class="step">
      <li class="step-title">操作步骤</li>
      <li>
        1.点击<a href="/batchTemplate.xlsx" download="搜索通用模板.xls">
          下载模板 </a
        >,下载导入表格模板
      </li>
      <li>2.请严格参照模板填充数据,否则可能无法导入数据</li>
      <li>3.导入数据,每次最多导入1000条数据</li>
    </ul>
    <div class="modal-footer">
      <a-button @click="handleModal">
        取 消
      </a-button>
      <a-button
        class="margin-left-15"
        type="primary"
        @click="handleModal('ok')"
      >
        确 认
      </a-button>
    </div>
  </div>
</template>
<script>
import XLSX from "xlsx"
export default {
  data() {
    return {
      valueList: []
    }
  },
  methods: {
    // 确认/关闭导入弹窗
    handleModal(type) {
      this.$emit("handleModal", type, this.valueList)
    },
    // 获取导入参数
    exportData(e) {
      let that = this
      let length = e.fileList.length > 0 ? e.fileList.length - 1 : 0
      // 拿取文件对象,注:不同框架获取到的对象可能不同,传统upload拿到的对象应该是e.target.file
      var f = e.fileList[length].originFileObj
      var binary = ""
      var wb
      var outdata
      var reader = new FileReader()
      reader.onload = function() {
        // 读取成Uint8Array,再转换为Unicode编码(Unicode占两个字节)
        var bytes = new Uint8Array(reader.result)
        var length = bytes.byteLength
        for (var i = 0; i < length; i++) {
          binary += String.fromCharCode(bytes[i])
        }
        wb = XLSX.read(binary, {
          type: "binary"
        })
        outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
        that.valueList = []
        outdata.forEach(item => {
          let data = Object.values(item)
          that.valueList = [...that.valueList, ...data]
        })
      }
      reader.readAsArrayBuffer(f)
    }
  }
}
</script>

<style lang="less" scoped>
.upload-content {
  width: 100%;
  height: 100%;
  padding: 30px;
  overflow: auto;
}
.step {
  width: 100%;
  height: 120px;
  margin-top: 20px;

  li {
    line-height: 30px;
  }
}
.step-title {
  font-weight: bold;
  margin-top: 20px;
  display: block;
}
.modal-footer {
  display: flex;
  justify-content: flex-end;
}
.list-box {
  width: 100%;
  max-height: 200px;
  overflow: auto;
}
</style>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值