引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>4.0.1</version>
</dependency>
动态合并单元格
List<List<String>> head = new ArrayList<>();
head.add(List.of("date"));
head.add(List.of("system"));
head.add(List.of("metric"));
head.add(List.of("value"));
List<Obj> list = new ArrayList<>();
list.add(new Obj( "2023-01-01", "system1", "metric","value"));
list.add(new Obj( "2023-01-01", "system1", "metric1","value1"));
list.add(new Obj( "2023-01-01", "system1", "metric2","value2"));
list.add(new Obj( "2023-01-01", "system1", "metric3","value3"));
list.add(new Obj( "2023-01-01", "system2", "metric4","value4"));
list.add(new Obj( "2023-01-01", "system2", "metric5","value5"));
list.add(new Obj( "2023-01-01", "system2", "metric6","value6"));
list.add(new Obj( "2023-01-01", "system2", "metric7","value7"));
String fileName = "template.xls";
File file = new File(fileName);
// 内容的策略(设置合并单元格居中)
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(new WriteCellStyle(),contentWriteCellStyle);
LoopMergeStrategy loopMergeStrategy = new LoopMergeStrategy(list.size(),0);
LoopMergeStrategy loopMergeStrategy1 = new LoopMergeStrategy(4,1);
EasyExcel.write(file)
.head(head)
.sheet()
// 开启相等值 行合并,从行索引1(excel中第二行)开始合并, 指定跨行合并的列索引
.registerWriteHandler(loopMergeStrategy)
.registerWriteHandler(loopMergeStrategy1)
.registerWriteHandler(horizontalCellStyleStrategy)
.doWrite(list);
System.out.println("导出成功");
}
@Data
@AllArgsConstructor
static class Obj{
private String date;
private String system;
private String metric;
private String value;
}
标签:01,Obj,示例,easyExcel,2023,list,add,使用,new
From: https://www.cnblogs.com/BitX/p/18305683