javaEasyExcel_0">基于java线程池和EasyExcel实现异步导出
1.controller层
java">@GetMapping("export")
public void exportExcel(HttpServletResponse response) throws IOException, InterruptedException {exportService.exportExcel(response);
}
2. service
java"> public void exportExcel(HttpServletResponse response) throws IOException, InterruptedException {setExportHeader(response);Long count = salariesMapper.selectCount(null);Long pageSize = 40000L;Long pageCount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;int pages = pageCount.intValue();ExecutorService executorService = Executors.newFixedThreadPool(pages);CountDownLatch countDownLatch = new CountDownLatch(pages);Map<Integer, Page<Salaries>> pageMap = new HashMap<>();for (int i = 0; i < pages; i++) {int finalI = i;executorService.submit(() -> {Page<Salaries> page = new Page<>();page.setCurrent(finalI + 1);page.setSize(pageSize);Page<Salaries> selectPage = salariesMapper.selectPage(page, null);pageMap.put(finalI, selectPage);countDownLatch.countDown();});}countDownLatch.await();executorService.shutdown();try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), Salaries.class).build()) {for (Map.Entry<Integer, Page<Salaries>> entry : pageMap.entrySet()) {Integer num = entry.getKey();Page<Salaries> salariesPage = entry.getValue();WriteSheet writeSheet = EasyExcel.writerSheet(num, "模板" + num).build();excelWriter.write(salariesPage.getRecords(), writeSheet);}}}