0

I'm a hobbyist trying to read an Excel file in order to change its format.

I want to look at columnIndex(0) to see if there is any text, if there is there are items at index (2–4) through row (+1 – 3) from that cell which I need to copy (never mind that, it's not the problem).

However, there are a lot of empty cells at columnIndex(0) which throw a NullPointerException because they 'don't exist'. I've been trying several cell checks using (cell == null) and .getCellTypeEnum etc. None seem to work.

Do you guys has any tips on how to circumvent this?

My staring code below:

// loading stuff

int row = 0;
int rowTot = sheet.getLastRowNum();

while (row < rowTot) {

    for (Cell cell : sheet.getRow(row)) {
        if (cell.getColumnIndex() == 0) {

            if (cell == null) {
                System.out.println("empty");
            } else {
                String text = cell.getStringCellValue();
                System.out.println(text);
            }
        }
    }
    row++;

// closing
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Sumerechny
  • 148
  • 10
  • 3
    @Sumerechny `cell.getColumnIndex() […] if (cell == null` Do you see it? – Biffen Apr 12 '18 at 10:56
  • I don't see `columnIndex(0)` in your code. – lexicore Apr 12 '18 at 11:00
  • Read the [docs - org.apache.poi.ss.usermodel.Cell#getStringCellValue](https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html#getStringCellValue--): "For numeric cells we throw an exception. For blank cells we return an empty string. For formulaCells that are not string Formulas, we throw an exception." – Mr. Polywhirl Apr 12 '18 at 11:00
  • @Biffen agree with you,need to first check if it null and then do other things – flyingfox Apr 12 '18 at 11:02
  • 1
    Check `cell == null` before you do `cell.getColumnIndex()` – LenglBoy Apr 12 '18 at 11:02
  • Thanks for the input everyone! The problem also surfaced with 'null' rows which is also solved. I need to keep learning, again; Thanks! – Sumerechny Apr 12 '18 at 18:16

1 Answers1

-2

Put it inside a try catch block.

Sr7
  • 86
  • 1
  • 9