多sheet页导出
核心代码就是下图里面的,使用EasyExcel.writeSheet创建一个sheet,然后用excelWriter写入就行了,很简单
@GetMapping("downloadMultiSheet")public void downloadMultiSheet(HttpServletResponse response) throws IOException {// 导出excel如果失败会返回jsontry {response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");response.setCharacterEncoding("utf-8");// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");response.setHeader("Content-disposition", "attachment;filename*=" + fileName + ".xlsx");ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();// 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样。// sheetNo从0开始WriteSheet writeSheet = EasyExcel.writerSheet(0, "用户").head(User.class).build();// 去数据库查找数据List<User> users = userService.list();excelWriter.write(users, writeSheet);writeSheet = EasyExcel.writerSheet(1, "部门").head(Department.class).build();// 去数据库查找数据List<Department> departments = departmentService.list();excelWriter.write(departments, writeSheet);// 写完要关闭,否则缓冲区数据会丢失excelWriter.close();} catch (Exception e) {// 重置responseresponse.reset();response.setContentType("application/json");response.setCharacterEncoding("utf-8");Map<String, String> map = MapUtils.newHashMap();map.put("status", "failure");map.put("message", "下载文件失败" + e.getMessage());response.getWriter().println(JSON.toJSONString(map));}}
多sheet导入
核心代码如图所示,使用EasyExcel.readSheet读取不同的sheet
@PostMapping("uploadMultiSheet")public Result uploadMultiSheet(@RequestPart MultipartFile file) throws IOException {try (ExcelReader excelReader = EasyExcel.read(file.getInputStream()).build()) {// 这里为了简单 所以注册了 同样的head 和Listener 自己使用功能必须不同的Listener// sheetNo从0开始ReadSheet readSheet1 =EasyExcel.readSheet(0).head(User.class).registerReadListener(new PageReadListener<User>(users -> {userService.saveBatch(users);})).build();ReadSheet readSheet2 =EasyExcel.readSheet(1).head(Department.class).registerReadListener(new PageReadListener<Department>(departments -> {departmentService.saveBatch(departments);})).build();// 这里注意 一定要把sheet1 sheet2 一起传进去,不然有个问题就是03版的excel 会读取多次,浪费性能excelReader.read(readSheet1, readSheet2);}return resultOk();}