代码
@RestController
@RequestMapping("test")
public class TestController {
@GetMapping("exportExcel")
public void exportExcel(HttpServletResponse response) {
String fileName = "test.xlsx";
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
Map<String, List<?>> map = dataService();
try {
exportExcelUtil(response, map);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
public Map<String, List<?>> dataService() {
ArrayList<Person> personList1 = new ArrayList<>();
ArrayList<Person> personList2 = new ArrayList<>();
ArrayList<Person> personList3 = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
Person liu = new Person("刘" + i, i, "xian");
personList1.add(liu);
personList2.add(liu);
personList3.add(liu);
}
Map<String, List<?>> map = new HashMap<>();
map.put("列表1", personList1);
map.put("列表2", personList2);
map.put("列表3", personList3);
return map;
}
public void exportExcelUtil(HttpServletResponse response, Map<String, List<?>> map) throws IOException, InterruptedException {
int threadCount = map.size();
AtomicInteger count = new AtomicInteger(-1);
ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
CountDownLatch i = new CountDownLatch(3);
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
for (String sheetName : map.keySet()) {
List<?> dataList = map.get(sheetName);
Class<?> aClass = dataList.get(0).getClass();
executorService.execute(() -> {
int k = count.incrementAndGet();
WriteSheet sheet = EasyExcel.writerSheet(k, sheetName).head(aClass).build();
synchronized (excelWriter) {
excelWriter.write(dataList, sheet);
}
i.countDown();
});
}
i.await();
excelWriter.finish();
executorService.shutdown();
}
}