前端代码如下:
importExcelBtn : function(){if(this.dialogImportExcel.fileList==null || this.dialogImportExcel.fileList.length==0){this.$message.error('文件必须上传');return}//var querystring = require('querystring') //原来用querystring 这种形式传值//var param = {}//this.importExcel(querystring.stringify(param))//后台捕获不到文件数据const multiForm = new FormData()//构建 FormData对象if (this.dialogImportExcel.fileList !== null && this.dialogImportExcel.fileList.length > 0) {this.dialogImportExcel.fileList.forEach(file => {multiForm.append('files', file);});}multiForm.append('isClear', this.dialogImportExcel.isClear)let loadingInstance = this.$loading({lock: true,background: "rgba(0, 0, 0, 0.7)",text: "正在导入数据,请不要刷新或关闭页面",});this.importExcel(multiForm).then(resp => {this.$message({type: 'success',message: '导入数据成功!'});this.dialogImportExcelVisible = false;this.getSysConfig();loadingInstance.close();//关闭loading}).catch(() => {loadingInstance.close();//关闭loading });},
后端代码如下:
@PostMapping(value = "/importExcel")public Response<String> importExcel( HttpServletRequest request,@RequestParam(value = "isClear", required = false) String isClear,@RequestParam(value = "files", required = false) List<MultipartFile> files) {long start=System.currentTimeMillis();try {synchronized (this) {if (files.size()>0) {MultipartFile multipartFile = files.get(0);InputStream inputStream = multipartFile.getInputStream();;try {List<EntityVo> list = EasyExcel.read(inputStream).head(EntityVo.class).sheet().doReadSync();List<Entity> dataslist=new ArrayList<>();if(list!=null&&list.size()>0){业务处理对应的数据}else {return Response.error("请导数有数据的excel。");}} finally {try {if (inputStream != null) {inputStream.close();}} catch (IOException e) {e.printStackTrace();}}}}System.out.println("运行时间:"+(System.currentTimeMillis()-start));return Response.ok("保存成功");} catch (Exception e) {e.printStackTrace();return Response.error("上传失败");}}