文章目录
业务需求:实现方式:具体步骤:1、引入组件:2、data中定义:3、methods中方法:业务需求:
批量导入Excel文件
实现方式:
使用组件upload
具体步骤:
1、引入组件:
<el-uploadaccept=".xlsx, .xls" //文件类型:file-list="fileList" //存储文件的数组:action="actionUrl" //请求的url:before-upload="beforeUploadFile" //文件上传之前的钩子:on-exceed="exceedFile" //文件超出个数时的钩子:on-success="uploadSuccess" //文件上传成功时的钩子:show-file-list="isShowFile" //是否显示文件上传列表multiple //支持多文件上传:limit="limitNum" //文件上传个数限制><el-button type="primary" style="margin-left:0px">导入Excel</el-button></el-upload>
2、data中定义:
fileList: [], //excel 文件列表limitNum: 3, //选择文件个数actionUrl: "/api/teach/importCourse", //上传文件urlisShowFile: false //文件列表是否显示 默认不显示
3、methods中方法:
//文件上传之前的钩子beforeUploadFile(file) {console.log("before upload");console.log(file.size);var FileExt = file.name.replace(/.+\./, "");if (["xls", "xlsx"].indexOf(FileExt.toLowerCase()) === -1) {this.$message({type: "warning",message: "请上传后缀名为xls、xlsx的附件!"});return false;}//file.size 以字节为单位this.isLt2k = file.size / 2048 < 100 ? "1" : "0";if (this.isLt2k === "0") {this.$message({message: "上传文件大小不能超过100k!",type: "error"});}return this.isLt2k === "1" ? true : false;},//文件超出个数时的钩子exceedFile(files, fileList) {console.log("文件超出个数:", files);this.$message.warning(`只能选择 ${this.limitNum} 个文件,当前共选择了 ${files.length +fileList.length} 个`);},
//文件上传成功时的钩子uploadSuccess(response, file, fileList) {console.log("上传文件", response.data);console.log("返回状态", response.code);console.log(fileList);if (response.code != "0000") {this.excelData = response.data;this.exportErrorFile();return this.$message.error("导入失败!");} else {this.isShowFile = true;return this.$message.success("导入成功!");}},