基于Apache POI库,对excel指定列,如果相邻的cell单元格值相同,则向下合并

/**
     * 对指定列,如果相邻的cell单元格值相同,则向下合并
     * 
     * @param sheet
     * @param startRowIndex 开始行索引
     * @param columIndex   指定列索引
     * @throws Exception
     */
    public void mergeCellsByColumIndex(Sheet sheet,int startRowIndex,int columIndex) {
        try {
            //创建一个映射,用于存储每个单元格的值及其对应的行索引列表
            Map<String, Integer> cellValues = new HashMap<>();
            int rows = sheet.getPhysicalNumberOfRows();
            for(int rowIndex = startRowIndex ;rowIndex < rows; rowIndex++) 
            {
                Row row = ExcelUtil.getRow(sheet,rowIndex);
                Cell cell = row.getCell(columIndex);
                if (cell != null) {
                    String cellValue = cell.getStringCellValue();
                    if (!cellValues.containsKey(cellValue)) {
                        cellValues.put(cellValue, rowIndex);
                    } else {
                        int firstRowIndex = cellValues.get(cellValue);
                        //cell不能与已经合并过的cell进行合并,先拆分
                        removeMergedRegion(sheet,firstRowIndex,rowIndex,columIndex,columIndex);
                        // 如果已经存在相同的值,则合并单元格
                        sheet.addMergedRegion(new CellRangeAddress(firstRowIndex, rowIndex, columIndex, columIndex));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 拆分一个区域内的所有合并单元格(一个区域,合并的单元格得全部在这个区域内,待整理一个不是ALL In区域的拆分API)
     * 
     * @param sheet
     * @param cellRowStart 区域开始行
     * @param cellRowEnd   区域结束行
     * @param cellColStart 区域开始列
     * @param cellColEnd   区域结束列
     * @throws Exception
     */
    public static void removeMergedRegion(Sheet sheet, int cellRowStart, int cellRowEnd, int cellColStart,
            int cellColEnd) throws Exception {
        for (int i = sheet.getNumMergedRegions() - 1; i >= 0; i--) {
            CellRangeAddress region = sheet.getMergedRegion(i);
            int intFirstRow = region.getFirstRow(); // 合并单元格CELL起始行
            int intFirstCol = region.getFirstColumn(); // 合并单元格CELL起始列
            int intLastRow = region.getLastRow(); // 合并单元格CELL结束行
            int intLastCol = region.getLastColumn(); // 合并单元格CELL结束列
            // 判断合并单元格是在区域里面
            if (intFirstRow >= cellRowStart && intLastRow <= cellRowEnd && intFirstCol >= cellColStart
                    && intLastCol <= cellColEnd) {
                Row firstRow = sheet.getRow(region.getFirstRow());
                Cell firstCellOfFirstRow = firstRow.getCell(region.getFirstColumn());
                sheet.removeMergedRegion(i);
            }
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值