Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read Excel cell having null values too in Java...?

I'm using Apache POI 3.6. I've a column which is blank. I would like to be able to read it and then move to the next column. Even if I could resolve the NullPointerException problem I could not get to the next cell.

Here's my code snippet :

HSSFCell cell = row.getCell(c);
String value = null;

switch (cell.getCellType()) {

    case HSSFCell.CELL_TYPE_FORMULA:
        value = "FORMULA value=" + cell.getCellFormula();
        break;

    case HSSFCell.CELL_TYPE_NUMERIC:
        value = "NUMERIC value=" + cell.getNumericCellValue();
        break;

    case HSSFCell.CELL_TYPE_STRING:
        value = "STRING value=" + cell.getStringCellValue();
        break;

    case HSSFCell.CELL_TYPE_BLANK:
        value="";
        break;

    case HSSFCell.CELL_TYPE_ERROR:
        value="error";
        break;

    default:
        break;
}

System.out.println("CELL col=" + cell.getColumnIndex() + " VALUE=" + value);

How can I resolve my problem?

like image 870
Venkat Avatar asked Jun 28 '10 13:06

Venkat


3 Answers

I've finally got what I want. I thank mezmo for it. I want to share the exact code snippet to be changed. Just replace the line having :

HSSFCell cell = row.getCell(c);

with

HSSFCell cell=row.getCell(c, org.apache.poi.ss.usermodel.Row.CREATE_NULL_AS_BLANK );
like image 131
Venkat Avatar answered Nov 07 '22 06:11

Venkat


Well, you could check for null before your switch statement, or you could change which call to row.getCell you make. Checking the Javadoc for POI there are 2 forms, the first is what you are using, the second has an additional parameter, of the type Row.MissingCellPolicy, where you can pass a value that would automagically transform null cells into blanks.

like image 34
mezmo Avatar answered Nov 07 '22 05:11

mezmo


You need to check if cell!=null, because if a cell doesn't exist in a row, row.getCell(c) returns null

like image 33
Erich Kitzmueller Avatar answered Nov 07 '22 06:11

Erich Kitzmueller