模板excel: merge_template.xlsx 向模板excel中填充数据,模板sheet2可以正常填充并合并;模板sheet1中无法合并,代码抛出异常:
Exception in thread "main" java.lang.IllegalStateException: Cannot add merged region B12:B13 to sheet because it overlaps with an existing merged region (A11:D13).
触发Bug的代码
public class MergeTest {
public static final int SHEET_NO_1 = 0;
public static final int SHEET_NO_2 = 1;
public static void main(String[] args) throws IOException {
String fileName = "D:\\MergedExcel.xlsx";
Resource resource = new ClassPathResource("/merge_template.xlsx");
// 方案1
try (ExcelWriter excelWriter = EasyExcel.write(fileName).inMemory(true).withTemplate(resource.getInputStream()).build()) {
// 使用sheet2能生成目标文件,使用sheet1就会报错
WriteSheet writeSheet = EasyExcel.writerSheet(SHEET_NO_1).registerWriteHandler(new SheetWriteHandler() {
@Override
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
// 写10行数据,将第2列单元格,每两行行合并一次
Sheet sheet = writeSheetHolder.getSheet();
int startRow = 0;
for (int j = 0; j < 5; j++) {
int lastRow = startRow + 1;
System.out.println(String.format("%s_%s", startRow, lastRow));
CellRangeAddress cellRangeAddress = new CellRangeAddress(startRow, lastRow, 1, 1);
sheet.addMergedRegionUnsafe(cellRangeAddress);
startRow += 2;
}
}}).build();
excelWriter.fill(mockData(), FillConfig.builder().forceNewRow(true).build(), writeSheet);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("export success");
}
private static List<Map<String, String>> mockData() {
List<Map<String, String>> dataList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Map<String, String> map = new HashMap<>();
map.put("a", "1");
map.put("b", "2");
map.put("c", "3");
map.put("d", "4");
dataList.add(map);
}
return dataList;
}
}
提示的异常或者没有达到的效果
异常:
Exception in thread "main" java.lang.IllegalStateException: Cannot add merged region B12:B13 to sheet because it overlaps with an existing merged region (A11:D13).
想要的效果: