Closed wurainren closed 4 years ago
使用的版本是v2.1.3
如果只需要合并一次,请使用com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy
多谢答复。 那合并多次呢?有没有比较好的解决方案?
@wurainren ,怀疑你的合并区域与默认的表头合并冲突了,建议先取消默认的表头合并,再自定义合并单元格。看下POI的addMergedRegion、addMergedRegionUnsafe和validateMergedRegions方法。可参考以下代码:
@Test
public void dynamicHeadWrite() {
String fileName = TestFileUtil.getPath() + "dynamicHeadWrite" + "1" + ".xlsx";
EasyExcel.write(fileName)
.registerWriteHandler(CellMergeStrategy())
//取消默认的表头合并
.automaticMergeHead(false)
// 这里放入动态头
.head(head()).sheet("模板")
// 当然这里数据也可以用 List<List<String>> 去传入
.doWrite(data());
}
private CellWriteHandler CellMergeStrategy() {
return new CellWriteHandler() {
@Override
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
Row row, Head head, Integer columnIndex, Integer relativeRowIndex,
Boolean isHead) {
}
@Override
public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
}
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex,
Boolean isHead) {
int rowIndex = cell.getRowIndex();
int columnIndex = cell.getColumnIndex();
//自己指定需要合并的单元格区域
if (rowIndex == 0 && columnIndex == 0) {
CellRangeAddress cellRangeAddress = new CellRangeAddress(rowIndex, rowIndex, columnIndex,
columnIndex + 1);
writeSheetHolder.getSheet().addMergedRegionUnsafe(cellRangeAddress);
}
}
};
}
异常代码