vue+elementUl导入文件方式(判断文件格式)

目录

elementUl导入文件(判断文件格式)

判断文件格式的思路

vue element导出导入

导出(下载)

导入(上传)

elementUl导入文件(判断文件格式)

使用el-elment 的el-dropdown组件来写下拉菜单效果。

下载模板比较简单,直接点击跳转页面,用window.open打开一个新的浏览器窗口方式下载模板文件。

选择文件,用组件el-upload。需要做一个提示“只能上传Excel文件”,用el-tooltip组件。

上传文件需要在before-upload进行判断文件格式。

判断文件格式的思路

是获取文件的后缀名,如果不是.xlsx就返回false,提示“文件格式只能是.xlsx!”

获取文件后缀名用到了2个方法。lastIndexOf()和substring()

lastIndexOf() 方法可返回一个指定的字符串值最后出现的位置,在一个字符串中的指定位置从后向前搜索

stringObject.substring(start,stop) 参数描述
start必需。一个非负的整数,规定要提取的子串的第一个字符在 stringObject 中的位置。
stop

可选。一个非负的整数,比要提取的子串的最后一个字符在 stringObject 中的位置多 1。

如果省略该参数,那么返回的子串会一直到字符串的结尾。

html

<el-dropdown style="margin-left: 10px"> <el-button type="primary"> 导入教师 <i class="el-icon-arrow-down el-icon--right"></i> </el-button> <el-dropdown-menu slot="dropdown"> <el-dropdown-item> <span @click="modelDown">下载模板</span> </el-dropdown-item> <el-dropdown-item> <el-upload ref="upload" action="/api/teacher/import" :limit="1" :data="uploadFile" :on-error="uploadError" :before-upload="beforeUpload" :on-success="uploadSuccess" > <div class="right"> <el-tooltip class="item" effect="dark" content="只能上传Excel文件" placement="right" > <el-button type="text">选择文件</el-button> </el-tooltip> </div> </el-upload> </el-dropdown-item> </el-dropdown-menu> </el-dropdown>

data:

data() { return { uploadFile: {}, //拼接导入文件参数 tableData: [], // 页面table显示的数据 }; },

methods

// 下载模版 modelDown() { window.open( "https://linkjoint-star.oss-cn-hongkong.aliyuncs.com/excel-template/教师导入模板.xlsx" ); }, // 提取文件后缀名 getSuffix(str) { const fileExtension = str.substring(str.lastIndexOf(".") + 1); return fileExtension; }, //导入前判断 beforeUpload(file) { let suffix = this.getSuffix(file.name); if (suffix !== "xlsx") { this.$message.error("文件格式只能是.xlsx"); return false; } }, //导入完成后提示 uploadSuccess(res, file) { console.log("res", res); if (res.status_code == 200) { if (res.data.status == 200) { this.$message({ message: `${res.data.msg}`, type: "success" }); this.getData(); } else { this.$message({ message: `${res.data.msg}`, type: "warning" }); } } else { this.$message.error("服务器错误"); } this.$refs.upload.clearFiles(); }, //导入错误提示 uploadError(err, file) { let error = JSON.parse(err.message); console.log(file); if (error.status_code == 422) { this.$message.error(error.message); } this.$refs.upload.clearFiles(); }, vue element导出导入 导出(下载)

Vue+Element后端导出Excel

从后台导出时,刚取到的文件是个流文件,需要把流文件进行转换。

<el-button class=".el-dropdown-menu__item i"  type="primary"  icon="el-icon-upload2" @click="downloadTemplate()" >导出模板</el-button>  downloadTemplate() {       exportTemplate()         .then(res => {           if (!res) {             return;           }           // 兼容IE浏览器           if (window.navigator && window.navigator.msSaveOrOpenBlob) {             window.navigator.msSaveOrOpenBlob(               new Blob([res.data]),               `文件名称.xlsx`             );           } else {             let url = window.URL.createObjectURL(new Blob([res.data])); //取到url。创建一个 DOMString,其中包含一个表示参数中给出的对象res的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。             let link = document.createElement("a"); //触发鼠标事件对象             link.style.display = "none"; //清除a标签样式             link.href = url; //设置下载地址             link.setAttribute("download", `文件名称.xlsx`); //给a标签添加download属性,并为其赋值             document.body.appendChild(link); //向节点添加一个子节点             link.click(); //执行click事件           }         })         .catch(error => {         });     },

前端导出Excel的方法,后期有机会再总结吧。

导入(上传)

Vue+Element后端导入Excel

先读取excel,通过接口把读出的数据result传给后台

 <el-upload     ref="upload"     :show-file-list="false"     :on-change="readExcel"     :auto-upload="false"     :limit="1"     :action="'/api/xxxx/xxxxxxxxxxxxx/'"     accept=".xlsx"     style="width:100%;"   >   <el-button      type="primary"      class=".el-dropdown-menu__item i"      slot="trigger"      icon="el-icon-download"      >导入</el-button> </el-upload> import XLSX from "xlsx";

读取excel

// 读取excel     readExcel(file) {       var reader = new FileReader(); //启动读取指定的File 内容       reader.readAsArrayBuffer(file.raw); //当读取操作完成时,会触发一个 load 事件,从而可以使用 reader.onload 属性对该事件进行处理。       reader.onload = e => {        //获取文件数据         const data = e.target.result; //XLSX读取文件         const wb = XLSX.read(data, { type: "array" });  //获取第一张表         const wsname = wb.SheetNames[0];         const ws = wb.Sheets[wsname];         var result = XLSX.utils.sheet_to_json(ws, { header: 1 });         this.$refs.upload.clearFiles(); //清除当前 files         if (result.length < 2503) {           this.dataDetail(result);         } else {           this.$message("每次导入数据最多2500条");         }         return result;       };     }, //通过接口把读出来的result传给后台 dataDetail(result) { //result内容格式的校验、必填项的校验   importReord(result)         .then(res => {             this.getRecordList();             if (res.data.msg == "批量新增成功") {               this.$message({                 message: "数据导入成功",                 type: "success"               });             }           })        .catch(error => {             if (error.response.status == 403) {               this.$message.error("无操作权限");             } else {               this.$message.error("数据导入失败");             }           }); }

校验时间格式

格式 : 2020-02-12 12:00

 //校验时间格式     istimeCheck(keyword) {       // let emIP = this.periodCheck.replace(/\s+/g, ""); //循环去空       let emIP = this.periodCheck.replace(/(^\s*)|(\s*$)/g, ""); //去除首尾空格       let timeArray = emIP.split("-"); //把字符串转换为数组       var result = timeArray.map(function(item, index, timeArray) {         // var reg = /^[1-9]\d{3}.(0[1-9]|1[0-2]).(0[1-9][0-1][0-9]|0[1-9]2[0-3]|[1-2][0-9][0-1][0-9]|[1-2][0-9]2[0-3]|3[0-1][0-1][0-9]|3[0-1]2[0-3]):[0-5][0-9]$/;         var reg = /^((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3}).(((0[13578]|1[02]).(0[1-9]|[12][0-9]|3[01]))|((0[469]|11).(0[1-9]|[12][0-9]|30))|(02.(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00)).02.29)) ([0-1][0-9]|2[0-3]):([0-5][0-9])$/;         return reg.test(item);       });       if (result.indexOf(false) > -1) {         return false;       } else {         return true;       }     }

校验IP地址格式

格式 : 10.1.1.12 或 10.1.12/24

 //校验IP地址格式     isValidIP(keyword) {       let emIP = this.OValidIP.replace(/\s+/g, ""); //字符串去空       if (emIP.indexOf("/") > -1) {         var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\/(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;         return reg.test(emIP);       } else {         var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;         return reg.test(emIP);       }     },

注意:在进行格式检验时,一定要记得判断值为" "或者undefined的情况,否则很容易出现bug。

Vue+Element前端导入Excel

前端导入需要先读取excel,把读出的数据渲染在前端界面上(如:table表格中,此时如果刷新界面,那数据就会没有了),然后通过提交或者保存的方式传给后台。读取excel的方法上面已经有了。 

以上为个人经验,希望能给大家一个参考,也希望大家多多支持易知道(ezd.cc)。 

推荐阅读

    vue项目一些常见问题

    vue项目一些常见问题,组件,样式,**样式污染问题**同样的样式不需要在每个组件都复制组件内单独的样式加外层class包裹。加scope。否则只是

    01-Vue项目实战-网易云音乐-准备工作

    01-Vue项目实战-网易云音乐-准备工作,网易,项目,前言在接下来的一段时间,我会仿照网易云音乐,利用Vue开发一个移动端的网易云音乐项目。在做

    01- 第一天 spring boot2.3.1 +vue3.0 后台管理系统的研发

    01- 第一天 spring boot2.3.1 +vue3.0 后台管理系统的研发,自己的,后台,后台框架一直想开发一套完全属于自己的后台,但是18年的时候,曾经答

    Vue项目中 App.vue文件

    Vue项目中 App.vue文件,文件,内容, 在App.vue文件中,定义了一个id为app的div,在这个div板块中放置Helloworld组件,文件内容如下图所示:在

    1-Vue构造函数的生成

    1-Vue构造函数的生成,函数,属性,版本:@2.6.10环境:web ;思维图:www.processon.com/view/link/5…我们使用的Vue是一个经过层层加强的构造函数

    vue的跨域是什么意思

    vue的跨域是什么意思,跨域,浏览器,代理,请求,服务器,同源策略,在vue中,跨域是指浏览器不能执行其他网站的脚本;它是浏览器同源策略造成的,是浏览器

    Vue中如何实现表单验证

    Vue中如何实现表单验证,验证,表单验证,表单,用户名,元素,指令,随着web应用的不断发展,表单验证逐渐成为web开发过程中不可或缺的一部分。在Vue中

    用vue框架有什么好处

    用vue框架有什么好处,组件,项目,数据,优化,操作,框架,用vue的好处:1、Vue是组件化开发,减少代码的书写,使代码易于理解;2、可以对数据进行双向绑定;3

    Vue中的路由懒加载

    Vue中的路由懒加载,组件,路由,应用程序,懒加载,导入,函数,随着Web应用程序的复杂性不断增加,前端框架和库的使用也越来越广泛。Vue是一种流行的J

    vue路由模式有哪些

    vue路由模式有哪些,模式,浏览器,路由,请求,刷新,服务器,vue路由模式有:1、hash模式,使用URL的hash值来作为路由,支持所有浏览器;其url路径会出现“#

    如何封装组件vue

    如何封装组件vue,组件,函数,封装,复用,组件开发,维护,Vue 是一种流行的 JavaScript 框架,它可以帮助开发者快速构建交互式的 Web 应用。Vue 的一

    vue如何实现页面跳转

    vue如何实现页面跳转,页面跳转,新窗口,方法,标签,属性,函数,vue实现页面跳转的方法:1、通过<vue-link>标签实现新窗口打开;2、通过在单击事件或者