Apache POI:计算合并的单元格

时间:2014-03-27 11:58:41

标签: java apache-poi

我想计算在行中合并了多少个单元格?我在Excel中合并(缩放)它,在Java中我希望显示例如:"合并的单元格:4" (A1,B1,C1,D1)?

1 个答案:

答案 0 :(得分:0)

   Sheet sheet = workbook.getSheetAt(1);
   Iterator<Row> rowIterator = sheet.iterator();
   while(rowIterator.hasNext()) {
            
            Row row = rowIterator.next();
            
            Iterator<Cell> cellIterator = row.iterator();               
                        
            while(cellIterator.hasNext()) {
                Cell currentCell = cellIterator.next();
                
                // To get values of the merged cells
                
                for(int i = 0; i < sheet.getNumMergedRegions(); i++) {
                    
                    CellRangeAddress region = sheet.getMergedRegion(i);
                    
                    int colIndex = region.getFirstColumn(); // no of columns merged
                    int rownum = region.getFirstRow();      // no of rows merged
                    
                    System.out.println(i);
                    
                    if(rownum == currentCell.getRowIndex() && colIndex == currentCell.getColumnIndex()) {
                        System.out.println(region.getLastColumn() + " " + region.getFirstColumn());
                        System.out.println("merged cell name " + sheet.getRow(rownum).getCell(colIndex).getStringCellValue());
                    }
                }
            }
        }