Map<String, List<PortReportResultVo>> relayLinkAndPortMap = new HashMap<>(); 遍历这个map,value为要导出的数据,都在一个sheet页中分分成多块内容,每块内容的表头可以自定义为2行,用easyExcel实现详细代码
时间: 2024-02-01 17:15:02 浏览: 101
可以使用 EasyExcel 的 write 方法来实现将数据导出到 Excel 表格中,代码如下:
```java
// 遍历 map
for (Map.Entry<String, List<PortReportResultVo>> entry : relayLinkAndPortMap.entrySet()) {
String sheetName = entry.getKey(); // sheet 名称
List<PortReportResultVo> dataList = entry.getValue(); // 要导出的数据
// 自定义表头
List<List<String>> head = new ArrayList<>();
List<String> head0 = new ArrayList<>();
head0.add("表头1-1");
head0.add("表头1-2");
head0.add("表头1-3");
head.add(head0);
List<String> head1 = new ArrayList<>();
head1.add("表头2-1");
head1.add("表头2-2");
head1.add("表头2-3");
head.add(head1);
// 写入 Excel
EasyExcel.write(fileName)
.sheet(sheetName)
.head(head)
.registerWriteHandler(new CustomCellWriteHandler()) // 自定义单元格样式
.doWrite(dataList);
}
```
需要自定义单元格样式时,可以实现 CustomCellWriteHandler 接口,代码如下:
```java
public class CustomCellWriteHandler implements WriteHandler {
@Override
public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
}
@Override
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
// 设置第 1 行的单元格样式
writeSheetHolder.getSheet().getRow(0).getCell(0).setCellStyle(getCellStyle(writeWorkbookHolder.getWorkbook()));
writeSheetHolder.getSheet().getRow(0).getCell(1).setCellStyle(getCellStyle(writeWorkbookHolder.getWorkbook()));
writeSheetHolder.getSheet().getRow(0).getCell(2).setCellStyle(getCellStyle(writeWorkbookHolder.getWorkbook()));
// 设置第 2 行的单元格样式
writeSheetHolder.getSheet().getRow(1).getCell(0).setCellStyle(getCellStyle(writeWorkbookHolder.getWorkbook()));
writeSheetHolder.getSheet().getRow(1).getCell(1).setCellStyle(getCellStyle(writeWorkbookHolder.getWorkbook()));
writeSheetHolder.getSheet().getRow(1).getCell(2).setCellStyle(getCellStyle(writeWorkbookHolder.getWorkbook()));
}
@Override
public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteRowHolder writeRowHolder) {
}
@Override
public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteRowHolder writeRowHolder, WriteCellHolder writeCellHolder) {
}
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteRowHolder writeRowHolder, WriteCellHolder writeCellHolder) {
}
private CellStyle getCellStyle(Workbook workbook) {
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
return cellStyle;
}
}
```
阅读全文