Vue 前端读取excel表格生成js数组

2020-08-20  本文已影响0人  卡西卡西yu

用到的插件: xlsx

npm install xlsx --save
 <a-upload
     accept=".xls,.xlsx"
     :show-upload-list="false"
     action=""
     name="file"
     @change="exportData">
     <a-button icon="upload" class="my-upload">选择文件</a-button>
</a-upload>

不同前端框架获取到的对象可能不同,因此,需注意寻找自己获取到的对象中的正确File对象

exportData (e) {
        const that = this
        // 拿取文件对象,注:不同框架获取到的对象可能不同,传统upload拿到的对象应该是e.target.file
        var f = e.fileList[0].originFileObj  
        var binary = ''
        var wb
        var outdata
        var reader = new FileReader()
        reader.onload = function (e) {
          // 读取成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]])
           //outdata 就是你最后生成的数组
          console.log(outdata )
        }
        reader.readAsArrayBuffer(f)
      }

以上。

上一篇 下一篇

猜你喜欢

热点阅读