vue3 批量导入excel表

安装xlxs插件

npm install xlsx  //安装

import * as XLSX from "xlsx";  //引入

 



批量导入

里面引用了element-plus的loading和弹窗,不需要的可以去掉

 let excelloading;
    const importExcel = (e) => {  //导入excel
      var file = e.target.files[0];

      if(!file) return

      excelloading = ElLoading.service({  //加载
        lock: true,
        text: '表格处理中',
        spinner: 'el-icon-loading',
        background: 'rgba(0,0, 0, 0.6)'
      });

      var persons = []  //接收excel数据

      var fileReader = new FileReader();
      fileReader.onload = function(ev) {
          try {
              var data = ev.target.result,
                workbook = XLSX.read(data, {
                    type: 'binary'
                }), // 以二进制流方式读取得到整份excel表格对象
                persons = []; // 存储获取到的数据

                e.target.value = ''
          } catch (e) {
              console.log('文件类型不正确');
              excelloading.close()  //关闭加载
              return;
          }

          // 表格的表格范围,可用于判断表头数量是否正确
          var fromTo = '';
          // 遍历每张表读取
          for (var sheet in workbook.Sheets) {
              if (workbook.Sheets.hasOwnProperty(sheet)) {
                  fromTo = workbook.Sheets[sheet]['!ref'];
                  // console.log(fromTo);
                  persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                  break; // 如果只取第一张表,就取消注释这行
              }
          }

          if(!persons.length){
            ElMessage.error('不能上传空表格')
            excelloading.close()  //关闭加载
            return
          }

          // console.log(persons);

          var arr = []  //匹配表头的名字,只提取需要用到的数据,例如我需要表里的手机号就只拿手机号的数据
          persons.forEach(v => {
            if(!arr.find(k => k['手机号'] == v['手机号'])){
              arr.push(v)
            }
          })

          if(!persons.length){
            ElMessage.error('不能上传空表格')
            excelloading.close()  //关闭加载
            return
          }

            //业务逻辑写在这里,例如请求数据接口传送数据给后台

          
      };

      // 以二进制方式打开文件
      fileReader.readAsBinaryString(file);
    }

 

posted @ 2024-03-15 11:28  哈哈敲敲  阅读(125)  评论(0编辑  收藏  举报