EasyExcel多线程导出

代码

/**
 * @Author Hamster
 * @Date 2023/9/24 12:18
 * @Version 1.0
 */
@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();
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值