SheetInfoBean,java
package com.ly.cloud.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @Author
* @Date Created in 2024/1/19 12:27
* @DESCRIPTION: YxThingsExportDto - YzExportDto - ZxExportDto 三个sheet
* @Version V1.0
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SheetInfoBean {
/**
* sheet页名称
*/
private String sheetName;
/**
* sheet标题bean
*/
private Class<?> headClass;
/**
* sheet页数据
*/
private List<?> dataList;
}
List<YxThingsExportDto> exportList = deCopyYxList(yxThingsList);
List<ZxExportDto> zxExportList = deCopyZxList(zxList);
List<YzExportDto> yzExportList = deCopyYzList(yzList);
//上面这几个集合数3sheet表的数据
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
// 构造各个sheet页相关信息
List<SheetInfoBean> sheetList = new LinkedList<>();
sheetList.add(new SheetInfoBean("事项信息", YxThingsExportDto.class, exportList));
sheetList.add(new SheetInfoBean("材料", ZxExportDto.class, zxExportList));
sheetList.add(new SheetInfoBean("类型", YzExportDto.class, yzExportList));
long start = System.currentTimeMillis();
// 自动列宽 + 批注
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
CompletableFuture<Void> previousFuture = getVoidCompletableFuture(sheetList, excelWriter);
previousFuture.join(); // 等待所有sheet写入完成
excelWriter.finish(); // 关闭资源
long end = System.currentTimeMillis();
System.out.println(end - start);
写入 3个 sheet页? 的数据;并给指定的sheet加批注操作
private static CompletableFuture<Void> getVoidCompletableFuture(List<SheetInfoBean> sheetList, ExcelWriter excelWriter) {
ReentrantLock lock = new ReentrantLock(false);
CompletableFuture<Void> previousFuture = CompletableFuture.completedFuture(null);
for (SheetInfoBean bean : sheetList) {
CompletableFuture<Void> currentFuture = new CompletableFuture<>();
previousFuture.thenAcceptAsync(ignored -> {
lock.lock();
try {
WriteSheet writeSheet = EasyExcel.writerSheet(bean.getSheetName())
.head(bean.getHeadClass())
.build();
// 给第一个: 事项类别信息 sheet 页添加批注
if ("事项信息".equals(bean.getSheetName())) {
List<WriteHandler> list = new ArrayList<>();
list.add(new YxCommentWriteHandler());
writeSheet.setCustomWriteHandlerList(list);
}
excelWriter.write(bean.getDataList(), writeSheet);
} catch (Exception e) {
throw new BusinessException(e);
} finally {
lock.unlock();
currentFuture.complete(null);
}
});
previousFuture = currentFuture;
}
return previousFuture;
}