首页 > 其他 > 详细

读取excel表格合并单元空值?

时间:2021-07-13 11:47:04      阅读:15      评论:0      收藏:0      [点我收藏+]

遍历读取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();
}
 

 

读取excel表格合并单元空值?

原文:https://www.cnblogs.com/lonson/p/15004819.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!