JAVA:Excel合并单元格数据读取

问题

使用poi解析excel后,若为合并单元格,仅第一行有数据,后面的合并单元格没有数据;

解决办法

判断cell是否为合并单元格,之后分类处理

 //判断是否为合并行
                if(isMergedRegion(sheet,j,0)){
                    int lastRow = getRowNum(cras,sheet.getRow(i).getCell(0),sheet);
                    for(;j<=lastRow;j++){
                        Row row = sheet.getRow(j);
                        if (row == null) {
                            continue;
                        }
                        if (row.getFirstCellNum() < 0) {
                            continue;
                        }
                        int readColumnCount = 0;
                        if (columnCount == null || columnCount > row.getLastCellNum()) {
                            readColumnCount = (int) row.getLastCellNum();
                        } else {
                            readColumnCount = columnCount;
                        }
                        List<Object> rowValue = new LinkedList<Object>();
                        // 解析sheet 的列
                        for (int k = 0; k < readColumnCount; k++) {
                            if(isMergedRegion(sheet,j,k)) {
                                rowValue.add(getMergedRegionValue(sheet, j, k));
                            }else{
                                Cell cell = row.getCell(k);
                                rowValue.add(getCellValue(wb, cell));
                            }
                        }
                        dataList.add(rowValue);
                    }

获取合并单元格数据代码

    /**
     * 获取合并单元格的值
     * @param sheet
     * @param row
     * @param column
     * @return
     */
    public static String getMergedRegionValue(Sheet sheet, int row, int column){
        int sheetMergeCount = sheet.getNumMergedRegions();

        for(int i = 0 ; i < sheetMergeCount ; i++){
            CellRangeAddress ca = sheet.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){
                    Row fRow = sheet.getRow(firstRow);
                    Cell fCell = fRow.getCell(firstColumn);
                    return getCellValue(fCell) ;
                }
            }
        }

        return null ;
    }

猜你喜欢

转载自blog.csdn.net/u011374582/article/details/83411629
今日推荐