Excel上傳,後臺讀取資料,處理合並單元格的特殊操作
阿新 • • 發佈:2018-11-20
/** * 判斷指定的單元格是否是合併單元格 * @return */ public static boolean isMergedRegion(XSSFSheet 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 true; } } } return false; }
/** * 獲取合併單元格的值 */ public Integer getMergedRegionValue(XSSFSheet xssfSheet, int row, int column) { int sheetMergeCount = xssfSheet.getNumMergedRegions(); XSSFCell fCell = null; //合併單元格取值 if(isMergedRegion(xssfSheet,row,column)){ for (int i = 0; i < sheetMergeCount; i++) { CellRangeAddress ca = xssfSheet.getMergedRegion(i); int firstColumn = ca.getFirstColumn(); int lastColumn = ca.getLastColumn(); int firstRow = ca.getFirstRow(); int lastRow = ca.getLastRow(); if (row >= firstRow && row <= lastRow) { if (column >= firstColumn && column <= lastColumn) { XSSFRow fRow = xssfSheet.getRow(firstRow); fCell = fRow.getCell(firstColumn); } } } }else{ //非合併單元格 fCell = xssfSheet.getRow(row).getCell(column); } return this.getCellVal(fCell); }
/** * 單元格資料型別不確定,統一單元格以String方式取值 * @param cell * @return */ public String getCellVal(XSSFCell cell){ String cellVal = ""; if(cell!=null){ //設定單元格型別 cell.setCellType(Cell.CELL_TYPE_STRING); cellVal = cell.getStringCellValue().trim(); } return cellVal; }