Excel上传,后台读取数据,处理合并单元格的特殊操作

/**
     * 判断指定的单元格是否是合并单元格
     * @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;
	}

 

猜你喜欢

转载自www.cnblogs.com/feixiangblogs/p/9986982.html