欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vue 前端导入execl数据

程序员文章站 2022-03-16 14:36:38
...

直接上我从别人那里复制的代码
html

<input
   type="file"
   @change="importf(this)"
   accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
 />

在当前页面引入

import XLSX from "xlsx"   // 没有就下载   npm install xlsx

js

// 导入
    importf(obj) {
      let _this = this;
      this.file = event.currentTarget.files[0];
      var rABS = false; //是否将文件读取为二进制字符串  
      var file = this.file;

      FileReader.prototype.readAsBinaryString = function (f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串  
        var pt = this;
        var workbook; //读取完成的数据  
        // var excelData;  
        var reader = new FileReader();
        reader.onprogress = function (e) {
          let total = file.size;
          _this.progress = (e.loaded / total) * 100;
        };
        reader.onload = function (e) {
          try {
            var bytes = new Uint8Array(reader.result);
            var length = bytes.byteLength;
            for (var i = 0; i < length; i++) {
              binary += String.fromCharCode(bytes[i]);
            }
            if (rABS) {
              workbook = XLSX.read(btoa(fixdata(binary)), { //手动转化  
                type: 'base64'
              });
            } else {
              workbook = XLSX.read(binary, {
                type: 'binary'
              });
            }
          } catch (e) {
            console.log('文件类型不正确');
            return;
          }
          var fromTo = '';
          for (var sheet in workbook.Sheets) {
            fromTo = workbook.Sheets[sheet]['!ref'];
            workbook.Sheets[sheet] = XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
            _this.excelData = workbook.Sheets
          }
          console.log(_this.excelData); // 输出为对象格式,也可输出位数组格式,我这样是为了配合后端
        };
        reader.readAsArrayBuffer(f);
      }
      var reader = new FileReader();
      if (rABS) {
        reader.readAsArrayBuffer(file);
      } else {
        reader.readAsBinaryString(file);
      }
    },

一次不错的抄袭,接下来该研究文件大小,判断过大时如何多次请求,有人会吗?

相关标签: 技术类