Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from next row in Excel sheet with POI

I'm using Apache POI to read an Excel document. I want to get the cell value from the next row if current is empty. For example, get from first row all not empty cell values and for empty cells: move to the next row and get the value. This the code I'm using to read the Excel document

                //every sheet has rows, iterate over them
                Iterator<Row> rowIterator = sheet.iterator();

                if (rowIterator.hasNext())
                    rowIterator.next();

                while (rowIterator.hasNext()) 
                {

                    String libelle="";
                    .....

                    //Get the row object
                    Row row = rowIterator.next();

                    //Every row has columns, get the column iterator and iterate over them
                    Iterator<Cell> cellIterator = row.cellIterator();

                    while (cellIterator.hasNext()) 
                    {
                        //Get the Cell object
                        Cell cell = cellIterator.next();

                        //check the cell type and process accordingly
                        //2nd column

                        switch(cell.getCellType()){
                        case Cell.CELL_TYPE_STRING:

                            ......
                            if (row.getCell(5) == null)
                            {
                               System.out.println("Cell is Empty in Column:" );

                            } else if (row.getCell(5).getCellType() == HSSFCell.CELL_TYPE_STRING)
                            {
                            libelle= row.getCell(5).getStringCellValue().trim();
                            }

...

like image 620
ItShine Avatar asked Oct 30 '25 21:10

ItShine


2 Answers

You can use Sheet.getRow(int rownumber) to get a row with a specific number. You can get the current row's number via Row.getRowNum() and the cell's index via Cell.getColumnIndex().

Therefore, the value of the cell in the next row would be

Row nextRow = sheet.getRow(row.getRowNum() + 1);
if (nextRow != null)
    String value = nextRow.getCell(curCel.getColumnIndex(), Row.CREATE_NULL_AS_BLANK).getStringCellValue();
like image 182
flo Avatar answered Nov 02 '25 11:11

flo


You can find out the current Cell.getRowIndex() to access the next Row via the Sheet.getRow(int) method if the calculated index is smaller than Sheet.getLastRowNum() in order to access Cell.getColumnIndex() of the Cell of the following Row.

like image 23
java_linux_user Avatar answered Nov 02 '25 11:11

java_linux_user



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!