Ashley
Ashley

Reputation: 491

Apache POI getStringCellValue() printing null

I'm getting a weird error while trying to read the Cell values through Apache POI in java:

 System.out.println(row.getCell(13, Row.CREATE_NULL_AS_BLANK).getStringCellValue()) 

is always printing null, even after specifying the Missing policy as Row.CREATE_NULL_AS_BLANK.My writing logic to the Cell is :

public void writeCell( String value, Sheet sheet, int rowNum, int colNum)
{
    Row row = sheet.getRow(rowNum);
    if (row == null)
    {
        row = sheet.createRow(rowNum);
    }
    Cell cell = row.createCell(colNum, Cell.CELL_TYPE_STRING);
    if (value == null)
    {
        return;
    }
    cell.setCellValue(value);
}

When I'm writing to Cell at colNum = 13 , the String value object is null. I'm not able to sort out this issue.

Upvotes: 0

Views: 2730

Answers (2)

Gagravarr
Gagravarr

Reputation: 48366

This line doesn't do what you seem to think it does:

System.out.println(row.getCell(13, Row.CREATE_NULL_AS_BLANK).getStringCellValue()) 

In effect, that's doing

Cell cell = row.getCell(13);
if (cell == null) { cell = row.createCell(13, Cell.CELL_TYPE_BLANK); }

So, if there is nothing in that cell, it creates it as an empty blank one

Then, you try doing:

 cell.getStringCellValue()

This only works for String cells, and in the missing case you've told POI to give you a Blank new cell!

If you really just want a string value of a cell, use DataFormatter.formatCellValue(Cell) - that returns a String representation of your cell including formatting. Otherwise, check the type of your cell before trying to fetch the value!

Upvotes: 1

briadeus
briadeus

Reputation: 605

The getStringCellValue() on the Cell interface would return "" if your code worked as supposed (setting the call blank).
Is it not possible that value for col id 13 is not null but "null"?

Upvotes: 0

Related Questions