流式导出与默认导出不同之处在于:流式导出采用生产者消费者模式,允许分批获取数据,分批写入Excel,且默认采用SXSSF模式,内存占用量极低,真正意义上实现海量数据导出,另外,流式导出支持zip压缩包等独有特性。
使用流式导出分为三步:
- 导出配置
- DefaultStreamExcelBuilder streamExcelBuilder = DefaultStreamExcelBuilder
- .of(ArtCrowd.class)
- .threadPool(Executors.newFixedThreadPool(10))// 线程池,可选
- .capacity(10_000)// 容量设定,在主动划分excel使用,可选
- .start();
- 数据追加
- streamExcelBuilder.append(dataList);
- 完成构建
- Workbook workbook = streamExcelBuilder.build();
附件导出示例:
- try (DefaultStreamExcelBuilder streamExcelBuilder = DefaultStreamExcelBuilder
- .of(ArtCrowd.class)
- .threadPool(Executors.newFixedThreadPool(10))
- .start()) {
- // 多线程异步获取数据并追加至excel,join等待线程执行完成
- List<CompletableFuture> futures = new ArrayList<>();
- for (int i = 0; i < 100; i++) {
- CompletableFuture future = CompletableFuture.runAsync(() -> {
- List<ArtCrowd> dataList = this.getDataList();
- // 数据追加
- defaultExcelBuilder.append(dataList);
- });
- futures.add(future);
- }
- futures.forEach(CompletableFuture::join);
- // 最终构建
- Workbook workbook = defaultExcelBuilder.build();
- AttachmentExportUtil.export(workbook, "艺术生信息", response);
- }
多文件导出示例:
设置Excel容量(capacity(10_000))
- try (DefaultStreamExcelBuilder defaultExcelBuilder = DefaultStreamExcelBuilder
- .of(ArtCrowd.class)
- .threadPool(Executors.newFixedThreadPool(10))
- .capacity(10_000)
- .start()) {
- ......
- // 最终构建
- List<Path> paths = defaultExcelBuilder.buildAsPaths();
- // do something
- }
zip导出示例:
设置Excel容量(capacity(10_000))
- try (DefaultStreamExcelBuilder defaultExcelBuilder = DefaultStreamExcelBuilder
- .of(ArtCrowd.class)
- .threadPool(Executors.newFixedThreadPool(10))
- .capacity(10_000)
- .start()) {
- ......
- // 最终构建
- Path zip = defaultExcelBuilder.buildAsZip("test");
- AttachmentExportUtil.export(zip,"finalName.zip",response);
- }
导出使用注解
- @ExcelTable(includeAllField,excludeParent,workbookType,sheetName,rowAccessWindowSize,useFieldNameAsTitle,defaultValue)
- @ExcludeColumn
- @ExcelColumn(title,order,dateFormatPattern,groups,defaultValue)对应注解详情请见:注解