1. 程式人生 > >java使用POI匯入Excel,並判斷合併單元格處,停止迴圈

java使用POI匯入Excel,並判斷合併單元格處,停止迴圈

public class ExcelCell {

    public static boolean isMergedRegion(HSSFSheet sheet,int row ,int column)
     {
      int sheetMergeCount = sheet.getNumMergedRegions();
      for (int i = 0; i < sheetMergeCount; i++) {
       Region ca = sheet.getMergedRegionAt(i);
       int firstColumn = ca.getColumnFrom();
       int lastColumn = ca.getColumnTo();
       int firstRow = ca.getRowFrom();
       int lastRow = ca.getRowTo();
       if(row >= firstRow && row <= lastRow)
       {
        if(column >= firstColumn && column <= lastColumn)
        {
         return true;
        }
       }
      }
      return false;
     }

}


===============================================

            rowNum = sheet.getPhysicalNumberOfRows();
            for (int i = 7; i < rowNum; i++) {
                
                row = sheet.getRow(i);
                if(ExcelCell.isMergedRegion(sheet, row.getRowNum(), 1)){
                    System.out.println("合併單元格,停止迴圈");
                    break;
                }
                try {
                    //獲取單元格物件
                    System.out.println(i+" "+row.getCell(0)+"==>"+row.getCell(0).getCellStyle().getIndention()+" ****"+row.getCell(1)+" "+row.getCell(2));
                    
                    
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }