ajax上传execl + easyexecl解析execl
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>上传下载Execl</title> <script src="../../js/jquery-1.9.1.min.js"></script> </head> <style> .outer { height: 200px; /*border: 1px #F2DEDE solid;*/ } .flex { display: flex; } .ai-c { align-items: center; } .jc-c { justify-content: center; } input { margin-top: 10px; } .loading { position: relative; } .loading:after { content: "加载中..."; position: absolute; top: 0; left: 0; width: 100%; height: 100%; box-sizing: border-box; padding: 100px; background: rgba(0, 0, 0, .6) url(../../img/loading.gif) no-repeat center 60px; color: #fff; text-align: center; } </style> <body> <div>上传下载Execl:</div> <div id="mainDiv" class="outer flex ai-c jc-c"> <div> <a href="/download" download="测试">下载Execl模板</a><br/> <label for="file">上传Execl:</label> <input type="file" id="file" name="file" value="" multiple><br/> <input type="submit" value="上传" onclick="submit()"> </div> </div> <script> var submit = function () { $("#mainDiv").addClass("loading"); var formData = new FormData(); formData.append('file', $('#file')[0].files[0]); formData.append('file', $('#file')[0].files[1]); $.ajax({ type: "post", url: "/upload2", cache: false, processData: false, contentType: false, data: formData, success: function (json) { $("#mainDiv").removeClass("loading"); alert("上传成功"); }, error: function (xhr) { $("#mainDiv").removeClass("loading"); alert("错误提示: " + xhr.status + " " + xhr.statusText); } }); } </script> </body> </html>
@ApiOperation("下载execl") @GetMapping("download") public void download(HttpServletResponse response) throws IOException { response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("utf-8"); String fileName = URLEncoder.encode("测试", "UTF-8"); response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx"); EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(data()); } @ApiOperation("文件上传") @PostMapping("upload") @ResponseBody public String upload(MultipartFile file) throws IOException { EasyExcel.read(file.getInputStream(), UploadData.class, new UploadDataListener(uploadDAO)).sheet().doRead(); return "success"; } @ApiOperation("多文件上传") @PostMapping("upload2") @ResponseBody public String upload2(MultipartHttpServletRequest request) throws IOException { List < MultipartFile > files = request.getFiles("file"); for (MultipartFile file : files) { EasyExcel.read(file.getInputStream(), UploadData.class, new UploadDataListener(uploadDAO)).sheet().doRead(); } return "success"; }
EasyExcel使用参考官方文档:https://alibaba-easyexcel.github.io/index.html