遍历读取excel表格时,读取合并单元格时,只能读取第一个单元格值,后面合并单元格值为空。

此时,需要判断当前单元格是否是合并单元格,是合并单元格的话,取第一个合并单元格值。

如何判断合并单元格呢?

 /**
     * 判断指定单元格是否是合并单元格
     * @param sheet   当前表格
     * @param row      表格的当前行
     * @param column  表格的当前列
     * @return
     */
    public static boolean 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 true;
                }
            }

        }

        return false;
    }

如何获取合并单元格的值?

 /**
     * 获取合并单元格的值
     * @param sheet   当前表格
     * @param row      表格的当前行
     * @param column  表格的当前列
     * @return
     */
    public static String getMergeRegionValue(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){
                    Row frow = sheet.getRow(firstRow);
                    Cell cell = frow.getCell(firstColumn);
                    return getCellValue(cell);
                }
            }
        }

        return null;

    }

/**
* 获取单元格的值
* @param cell
* @return
*/
public static String getCellValue(Cell cell){

if (cell == null) return "";
return cell.toString();
}