java excel合并内容相同的单元格

1、背景

最近在做导出的过程中,导出的excel,列值的内容有很多相同的部分,针对这部分需要进行单元格的合并。那么在java中是如何实现的呢?

2、实现

/**
 * excel 工具类
 *
 * @author huan.fu
 * @date 2023/3/21 - 20:25
 */
public class ExcelUtil {
    
    

    /**
     * 合并指定Excel sheet页、指定列中连续相同内容的单元格
     *
     * @param sheet    Excel sheet
     * @param startRow 从第几行开始, startRow的值从1开始
     * @param column   指定列
     */
    public static void mergeSameCellContentColumn(Sheet sheet, int startRow, int column) {
    
    
        int totalRows = sheet.getLastRowNum();
        int firstRow = 0;
        int lastRow = 0;
        // 上一次比较是否相同
        boolean isPrevCompareSame = false;
        String prevMergeAddress = null;
        String currentMergeAddress;
        // 从第几开始判断是否相同
        if (totalRows >= startRow) {
    
    
            for (int i = startRow; i <= totalRows; i++) {
    
    
                String lastRowCellContent = sheet.getRow(i - 1).getCell(column).getStringCellValue();
                String curRowCellContent = sheet.getRow(i).getCell(column).getStringCellValue();
                if (curRowCellContent.equals(lastRowCellContent)) {
    
    
                    if (!isPrevCompareSame) {
    
    
                        firstRow = i - 1;
                    }
                    lastRow = i;
                    isPrevCompareSame = true;
                } else {
    
    
                    isPrevCompareSame = false;
                    currentMergeAddress = firstRow + lastRow + column + column + "";
                    if (lastRow > firstRow && !Objects.equals(currentMergeAddress, prevMergeAddress)) {
    
    
                        sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, column, column));
                        prevMergeAddress = currentMergeAddress;
                    }
                }
                // 最后一行时判断是否有需要合并的行
                if ((i == totalRows) && (lastRow > firstRow)) {
    
    
                    currentMergeAddress = firstRow + lastRow + column + column + "";
                    if (!Objects.equals(currentMergeAddress, prevMergeAddress)) {
    
    
                        sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, column, column));
                    }
                }
            }
        }
    }
}

3、实现效果

实现效果

猜你喜欢

转载自blog.csdn.net/fu_huo_1993/article/details/129698080