POI判断某个单元格是否是合并单元格

来源:互联网 发布:科学革命的结构 知乎 编辑:程序博客网 时间:2024/05/20 03:41

有时我们需要读取复杂的excel的数据,比如下面表格:

xx起始单元格xxxxxxxx结束单元格xxxxxxxxxxxxxxxx

注:比如我们的数据是上面N个单元组成,且每个单元所占行数可能不同。第一列占据一列,中间数据每个占用一个单元格,最后一列与第一列占用相同的行数,这时我们需要获取起始单元格占用几行(起始行--结束行),获取到这些数据后我们就能读取中间单元格数据(这些数据可以作为上面单元的一个属性),下面给出具体代码:

private Result isMergedRegion(Sheet sheet,int row ,int column) {   
       int sheetMergeCount = sheet.getNumMergedRegions();   
       for (int i = 0; i < sheetMergeCount; i++) {   
             CellRangeAddress range = sheet.getMergedRegion(i);   
             int firstColumn = range.getFirstColumn(); 
             int lastColumn = range.getLastColumn();   
             int firstRow = range.getFirstRow();   
             int lastRow = range.getLastRow();   
             if(row >= firstRow && row <= lastRow){ 
                 if(column >= firstColumn && column <= lastColumn){ 
                return new Result(true,firstRow+1,lastRow+1,firstColumn+1,lastColumn+1);   
                 } 
             }
       } 
       return new Result(false,0,0,0,0);  
     } 


注:通过上面这个方法我们就能验证某个单元格是否是合并单元格,以及该单元格所属的合并单元格的开始行、结束行、起始列以及结束列,由于我们使用excel时习惯上把第一行当做行1(POI中第一行行号为0),所以每个数据都加了1.

Result是用来传递返回结果的一个类而已:

class Result{
public boolean merged;
public int startRow;
public int endRow;
public int startCol;
public int endCol;
public Result(boolean merged,int startRow,int endRow
,int startCol,int endCol){
this.merged = merged;
this.startRow = startRow;
this.endRow = endRow;
this.startCol = startCol;
this.endCol = endCol;
}
}

原创粉丝点击