首页 > 其他分享 >vue纯前端导入excel,获取excel的表格数据渲染el-table并纯前端分页实现方法

vue纯前端导入excel,获取excel的表格数据渲染el-table并纯前端分页实现方法

时间:2022-11-17 10:57:50浏览次数:74  
标签:el console log index 前端 excel item tab xlscList

因为项目开发的过程中不是所有的表格数据由后台处理返回,因为有些数据不需要在数据库落地,只做前端页面展示并且获取表格的数据上传即可,所以需要前端纯处理excel的数据。

第一步首先把插件安装好

npm install xlsx --save

第二步在vue页面中导入XLSX

<script>
    import XLSX from 'xlsx'
</script>

第三步页面实现

<el-upload ref="upload" action="/" :show-file-list="false" :on-change="importExcel" :auto-upload="false">
   <el-button class="d2-mt-10 d2-mb-10" slot="trigger" icon="el-icon-upload" type="primary">
      上传人员
   </el-button>
</el-upload>

<el-table :data="memberList" highlight-current-row border style="width: 100%" height="600" :header-cell-style="{background:'#eef1f6',color:'#606266'}" class="table-fixed-lineBug">
  <el-table-column prop="cyrxm" label="参会人姓名" align="center" min-width="150" show-overflow-tooltip/>
  <el-table-column prop="cyrjsmc" label="参会人角色" align="center" min-width="150" show-overflow-tooltip/>
  <el-table-column prop="sfzhm" label="身份证号码" align="center" min-width="200" show-overflow-tooltip/>
  <el-table-column prop="sjh" label="手机号码" align="center" min-width="150" show-overflow-tooltip/>
  <el-table-column prop="iszcr" label="是否主持人" align="center" width="110" show-overflow-tooltip/>
  <el-table-column prop="isgly" label="是否会议管理员" align="center" width="130" show-overflow-tooltip/>
  <el-table-column prop="ispt" label="是否旁听" align="center" width="130" show-overflow-tooltip/>
</el-table>
<el-pagination @current-change="handleCurrentChange(currentPage)" :current-page.sync="currentPage" :page-size="5" layout="total, prev, pager, next" :total="memberList.length" align="right">
</el-pagination>

第四步js

<script>  
    import XLSX from 'xlsx' 
    export default {
        name: '',
        components: {},
        props: {
        },
        data() {
            return {
                memberList: [],
                xlscList:[],
                wb: null,
                currentPage: 1,
            }
        },
        methods: {
            handleCurrentChange(index) {       //currentPage变动时触发,index值为当前页前端实现分页
            console.log(this.memberList)
                this.currentPage = index
                // this.memberLists = this.memberList.slice((index - 1) * 5, index * 5)             //将初始数据进行裁剪赋值给新数组
                this.$set(this._data,'memberLists',this.memberList.slice((index - 1) * 5, index * 5)  )
        },
            //第一步上传文件
            importExcel(file) {
                let self = this;
                const types = file.name.split(".")[1];
                const fileType = ["xlsx", "xlc", "xlm", "xls", "xlt", "xlw", "csv"].some(
                  item => item === types
                );
                console.log(fileType)
                if (!fileType) {
                   alert("格式错误!请重新选择");
                  return;
                }
                this.file2Xce(file).then(tab => {
                  // console.log(tab)
                  if (tab && tab.length > 0) {
                    this.tab = tab;
                    if (this.tab.length != 0) {
                      console.log(tab)
                      this.xlscList = [];
                      this.tab[0].sheet.forEach(item => {
                        // console.log(item.indexOf("C") != -1)
                        if (item.indexOf("") != -1) {
                          let inputInfo = item.split("'");//excel的数据类型都是text所以通过item.split("'")截取,拿到所以表的数据
                          if (inputInfo.length == 2) {
                            self.xlscList.push(inputInfo[1]);
                            // console.log(self.xlscList)
                          }
                        }
                      });
                    }
                    if (this.xlscList.length != 0) {
                      this.setInputToForm();
                    }
                  }
                });
            },
            //对组进行切割
            setInputToForm(){
                if (this.xlscList.length >= 7) {//判断表头的长度
                  /*
                  * 将一个数组分成几个同等长度的数组
                  * array[分割的原数组]
                  * size[每个子数组的长度]
                  */
                  this.xlscList=this.xlscList.slice(7)
                  // console.log()
                  let result = [];
                  let personnelList = []
                  for (var x = 0; x < Math.ceil(this.xlscList.length / 7); x++) {
                      var start = x * 7;
                      var end = start + 7;
                      result.push(this.xlscList.slice(start, end));
                  }
                  // console.log(result)
                  //获取每一个数组的第一个,第二个,第三个...通过push重新拼装成一个新的数组对象
                  for(let i = 0;i<result.length;i++) {
                    for(let j = 0;j<result[i].length;j++) {
                      if(j == 0) {
                        personnelList.push({cyrjsmc:result[i][j],cyrxm:result[i][j+1],sfzhm:result[i][j+2],sjhm:result[i][j+3],sfzcrmc:result[i][j+4],sfglymc:result[i][j+5],sfptmc:result[i][j+5]})
                      }
                    }
                  }
                  this.memberList = personnelList;
                  this.handleCurrentChange(1);
                }else{
                  this.$message({
                    message: '上传格式不對',
                    type: 'warning'
                  })
                }
            },
            file2Xce(file) {
                return new Promise(function(resolve, reject) {
                  const reader = new FileReader();
                  reader.onload = function(e) {
                    const data = e.target.result;
                    this.wb = XLSX.read(data, {
                      type: "binary"
                    });
                    const result = [];
                    this.wb.SheetNames.forEach(sheetName => {
                      result.push({
                        sheetName: sheetName,
                        sheet: XLSX.utils.sheet_to_formulae(this.wb.Sheets[sheetName])
                      });
                    });
                    resolve(result);
                  };
                  reader.readAsBinaryString(file.raw);
                });
            },
        }
    }
</script>

导入的excel格式

效果图

这样就轻松实现了,有什么不对的欢迎吐槽

本文转自 https://blog.csdn.net/weixin_39277183/article/details/115530518,如有侵权,请联系删除。

标签:el,console,log,index,前端,excel,item,tab,xlscList
From: https://www.cnblogs.com/zhubh/p/16898684.html

相关文章

  • 在MYSQL里,不能先select一个表的记录,再按此条件进行更新和删除同一个表的记录
    解决办法是,将select得到的结果,再通过中间表select一遍,这样就规避了错误,这个问题只出现于mysql,mssql和oracle不会出现此问题。MySQL根据字段删除重复值deletefromsites......
  • Android 中通过Intent传递类对象,通过实现Serializable和Parcelable接口两种方式传递对
    方式一:通过实现Serializable接口传递对象用一个小的Demo去理解,通过实现Serializable接口传递对象。效果图:具体讲解在代码注释中已经写出先创建一个对象:packagecom.exampl......
  • SpringClouldAlibaba 之 Sentinel流控规则同步到nacos(并重新生成镜像)
    前言上一篇我们将流控规则配置到了nacos让服务启动时拉取流控规则从而实现持久化但是是有一个缺陷的,毕竟在nacos中维护这个流控规则不太友好,毕竟sentinel为我们提供了可视......
  • Python selenium 插入图片
    方法一如果有上传图片按钮的,就比较简单了:browser.find_element_by_id("IdOfInputTypeFile").send_keys(os.getcwd()+"/image.png")browser.find_element_by_xpath("IdOfInpu......
  • celery 调用 scrapy
    celery调用scrapy需求如同调用函数般调用.定时或时时获取数据.实现fromcrochetimportsetup,wait_forfromscrapy.crawlerimportCrawlerProcessclassCra......
  • shell字符串截取报错 Bad substitution 的解决方法
    问题:脚本执行到截取字符串时,报错提示:Badsubstitution。原因:两种shell语言解释器bash和dash,这种情况是指向了dash解释器导致。解决方法:1.查看shell指向:l......
  • Babelfish for PostgreSQL
      BabelfishforPostgreSQL开源已快一月,不过全网还没有实践者总结。今天我们就测试看看,Babelfish到底是如何部署与使用的! BabelfishforPostgreSQL介绍我们先回......
  • VAB excel FIND使用
    求:多个表格内容相加公式:=PHONETIC(A2:A7)说明:Phonetic函数只能对字符型内容合并,数字不可以。求:前三位公式:=LEFT(A2,LEN(A2)-8)说明:LEN计算出总长......
  • kernel——字符设备驱动
    字符设备驱动的框架设备节点:inode,类型为字符设备,记录设备号设备号:内核确定驱动的唯一编号cdev:字符驱动对象框架代码驱动#include<linux/module.h>#include<linux......
  • 前端常见算法
    C:\Users\Administrator\Desktop\手写\01_instanceOf.jsfunctioninstance_of(target,origin){lettargetP=target.__proto__;letoriginP=origin.prototype;......