Nasreddin
Nasreddin

Reputation: 1647

How do I iterate all the rows in a spreadsheet (including null)

I am using apache poi to parse excel spreadsheet. According to the poi iterator guide, row iterator will skip the rows that are null. I wanted to iterate all rows, null or not. So I used for loop instead.

            Row row0 = sheet.getRow(0);
            for (Row row : sheet)
            {
                rowIndex ++;
                Cell cell = row.getCell(0);
                if (cell != null) {
                     System.out.println(rowIndex);
                }
            }

When I debugged it in Eclipse, for the following spreadsheet, row0 is null, however row in the first iteration of for loop is NOT null. The output (row index of first not null cell) is supposed to be 2, but it actually prints 1.

spreadsheet

debug in eclipse

Why is the first null row skipped by the for loop?

Upvotes: 1

Views: 7982

Answers (1)

Mateusz Dryzek
Mateusz Dryzek

Reputation: 661

For loop (in this case for-each loop) uses iterator (see Iterable interface https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html) to iterate through rows, so as you have written it will skip null values.

The way to include null values in iteration is to use traditional for loop (see Iterate over cells, with control of missing / blank cells section in http://poi.apache.org/spreadsheet/quick-guide.html#Iterator).

Upvotes: 2

Related Questions