easyexcel 合并单元格方法
时间: 2023-09-25 14:06:20 浏览: 86
easyexcel合并单元格
使用 EasyExcel 合并单元格需要使用 `@ExcelIgnoreUnmergedRegions` 注解来忽略未合并的单元格,否则会抛出异常。然后使用 `merge()` 方法来合并单元格。
以下是一个示例代码:
```java
@ExcelIgnoreUnmergedRegions
public class MergeCellDemo {
public static void main(String[] args) {
// 写法一:合并指定范围的单元格
EasyExcel.write("merge-cell.xlsx")
.sheet("Sheet1")
.head(head())
.registerWriteHandler(new MergeCellWriteHandler())
.doWrite(data());
// 写法二:使用注解合并单元格
EasyExcel.write("merge-cell-annotation.xlsx")
.sheet("Sheet1")
.head(head())
.doWrite(dataWithAnnotation());
}
private static List<List<String>> head() {
List<List<String>> head = new ArrayList<>();
List<String> row1 = new ArrayList<>();
row1.add("姓名");
row1.add("年龄");
row1.add("性别");
head.add(row1);
return head;
}
private static List<List<Object>> data() {
List<List<Object>> data = new ArrayList<>();
List<Object> row1 = new ArrayList<>();
row1.add("张三");
row1.add(20);
row1.add("男");
data.add(row1);
List<Object> row2 = new ArrayList<>();
row2.add("李四");
row2.add(22);
row2.add("女");
data.add(row2);
List<Object> row3 = new ArrayList<>();
row3.add("王五");
row3.add(25);
row3.add("男");
data.add(row3);
return data;
}
@MergeStrategy(name = "name", mergeType = MergeStrategy.MergeType.HORIZONTAL)
@ExcelIgnoreUnmergedRegions
private static List<MergeCellDemo> dataWithAnnotation() {
return Arrays.asList(
new MergeCellDemo("张三", 20, "男"),
new MergeCellDemo("李四", 22, "女"),
new MergeCellDemo("王五", 25, "男")
);
}
private String name;
private Integer age;
private String gender;
public MergeCellDemo(String name, Integer age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
// 省略 getter 和 setter 方法
}
```
其中,`MergeCellWriteHandler` 是自定义的一个合并单元格处理器,代码如下:
```java
public class MergeCellWriteHandler implements WriteHandler {
@Override
public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
}
@Override
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
}
@Override
public void afterWorkbookCreate(WriteWorkbookHolder writeWorkbookHolder) {
}
@Override
public void beforeWrite(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder) {
}
@Override
public void afterWrite(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder) {
}
@Override
public void afterRowCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer rowIndex, Integer relativeRowIndex, Boolean isHead) {
if (isHead) {
// 合并第一行的前三列
CellRangeAddress region = new CellRangeAddress(0, 0, 0, 2);
writeSheetHolder.getSheet().addMergedRegion(region);
}
}
}
```
注意,在写入 Excel 文件时,需要调用 `registerWriteHandler()` 方法注册合并单元格处理器。
阅读全文