0

How can i read for each row and cloumn 14 value into string variable in apache poi 4.

         while (rows.hasNext()) {
                Row currentRow = rows.next();
                System.out.println(currentRow);
                Iterator<Cell> cellsInRow = currentRow.iterator();
                while(cellsInRow.hasNext()) {
                    Cell currentCell = cellsInRow.next();
                    int cellIndex = currentCell.getColumnIndex();
                    int columnidx = 14;
                    String values = currentCell.getStringValue() //how can i get the  value for every row for column 14  
                }
            }

1 Answer 1

4

If you look at the documentation, i.e. the javadoc of Row, you will find the very handy getCell(int cellnum) method:

Get the cell representing a given column (logical cell) 0-based. If you ask for a cell that is not defined....you get a null.

Which means you shouldn't iterate all the cells:

while (rows.hasNext()) {
    Row currentRow = rows.next();
    Cell cell14 = currentRow.getCell(13); // 14th cell
    String value = (cell14 == null ? null : cell14.getStringCellValue());
    // use value here
}

Unrelated, but you shouldn't use iterator while loops. The code will be simpler and easier to read if you use a for-each loop, so instead of:

Iterator<Row> rows = sheet.rowIterator();
while (rows.hasNext()) {
    Row currentRow = rows.next();

    Iterator<Cell> cellsInRow = currentRow.iterator();
    while (cellsInRow.hasNext()) {
        Cell currentCell = cellsInRow.next();

    }
}

you should use:

for (Row currentRow : sheet) {

    for (Cell currentCell : currentRow) {

    }
}

See how much that improves the code?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.