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、实现效果

实现效果

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值