//定义列实体
@Data
public class ExcelCoordinate implements Serializable {
    private int firstRow;
    private int lastRow;
    private int firstCol;
    private int lastCol;
    public  ExcelCoordinate(int firstRow,int lastRow,int firstCol,int lastCol)
    {
        this.firstRow=firstRow;
        this.lastRow=lastRow;
        this.firstCol=firstCol;
        this.lastCol=lastCol;
    }
}

设置合并单元格规则容器

public class LoopMergeStrategyQuestion extends AbstractRowWriteHandler {

    private List<ExcelCoordinate> Coordinates;


    public LoopMergeStrategyQuestion(List<ExcelCoordinate> Coordinates) {
        this.Coordinates=Coordinates;
    }


    public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer relativeRowIndex, Boolean isHead) {
        if (!isHead) {
            for(var Coordinate :Coordinates)
            {
                if (relativeRowIndex % Coordinate.getFirstRow() == 0) {
                    CellRangeAddress cellRangeAddress = new CellRangeAddress(Coordinate.getFirstRow(), Coordinate.getLastRow(), Coordinate.getFirstCol(), Coordinate.getLastCol());
                    writeSheetHolder.getSheet().addMergedRegionUnsafe(cellRangeAddress);
                }
            }


        }
    }
}

使用:

List<ExcelCoordinate> ExcelCoordinates=new ArrayList<ExcelCoordinate>();
ExcelCoordinates.add(new ExcelCoordinate(i,i,j,k));
LoopMergeStrategyQuestion ClassSummaryLoopMergeStrategy=new LoopMergeStrategyQuestion(ExcelCoordinates);
ExcelWriter excelWriter = null;
excelWriter = EasyExcel.write(filePath).build();
writeSheet =EasyExcel.writerSheet(0, "sheet1" )
        .head(head)
        .registerWriteHandler(ClassSummaryLoopMergeStrategy)
        .build();
excelWriter.write(data, writeSheet);

表头中合并单元格:

将列名称连着写入就可以实现表头中的单元格合并