流式导出与默认导出不同之处在于:流式导出采用生产者消费者模式,允许分批获取数据,分批写入Excel,且默认采用SXSSF模式,内存占用量极低,真正意义上实现海量数据导出,另外,流式导出支持zip压缩包等独有特性。

    使用流式导出分为三步:

    • 导出配置
    1. DefaultStreamExcelBuilder streamExcelBuilder = DefaultStreamExcelBuilder
    2. .of(ArtCrowd.class)
    3. .threadPool(Executors.newFixedThreadPool(10))// 线程池,可选
    4. .capacity(10_000)// 容量设定,在主动划分excel使用,可选
    5. .start();
    • 数据追加
    1. streamExcelBuilder.append(dataList);
    • 完成构建
    1. Workbook workbook = streamExcelBuilder.build();

    附件导出示例:

    1. try (DefaultStreamExcelBuilder streamExcelBuilder = DefaultStreamExcelBuilder
    2. .of(ArtCrowd.class)
    3. .threadPool(Executors.newFixedThreadPool(10))
    4. .start()) {
    5. // 多线程异步获取数据并追加至excel,join等待线程执行完成
    6. List<CompletableFuture> futures = new ArrayList<>();
    7. for (int i = 0; i < 100; i++) {
    8. CompletableFuture future = CompletableFuture.runAsync(() -> {
    9. List<ArtCrowd> dataList = this.getDataList();
    10. // 数据追加
    11. defaultExcelBuilder.append(dataList);
    12. });
    13. futures.add(future);
    14. }
    15. futures.forEach(CompletableFuture::join);
    16. // 最终构建
    17. Workbook workbook = defaultExcelBuilder.build();
    18. AttachmentExportUtil.export(workbook, "艺术生信息", response);
    19. }

    多文件导出示例:

    设置Excel容量(capacity(10_000))

    1. try (DefaultStreamExcelBuilder defaultExcelBuilder = DefaultStreamExcelBuilder
    2. .of(ArtCrowd.class)
    3. .threadPool(Executors.newFixedThreadPool(10))
    4. .capacity(10_000)
    5. .start()) {
    6. ......
    7. // 最终构建
    8. List<Path> paths = defaultExcelBuilder.buildAsPaths();
    9. // do something
    10. }

    zip导出示例:

    设置Excel容量(capacity(10_000))

    1. try (DefaultStreamExcelBuilder defaultExcelBuilder = DefaultStreamExcelBuilder
    2. .of(ArtCrowd.class)
    3. .threadPool(Executors.newFixedThreadPool(10))
    4. .capacity(10_000)
    5. .start()) {
    6. ......
    7. // 最终构建
    8. Path zip = defaultExcelBuilder.buildAsZip("test");
    9. AttachmentExportUtil.export(zip,"finalName.zip",response);
    10. }

    导出使用注解

    • @ExcelTable(includeAllField,excludeParent,workbookType,sheetName,rowAccessWindowSize,useFieldNameAsTitle,defaultValue)
    • @ExcludeColumn
    • @ExcelColumn(title,order,dateFormatPattern,groups,defaultValue)对应注解详情请见:注解