Question

I'm trying to read some cells in a line, first 5 sheets using the same reading code were ok, but my 6th sheet is returning a null value in a specific cell even when the cell has value in the spreadsheet.

Has anyone seen this one before? How to solve it?

Thanks in advance!

PS.: here's the code I'm using to get the values, works fine 'til it reaches the 6th sheet. I can see that the Excel spreadsheet is filled but still getting a null.

private String getValorTexto(HSSFSheet sheet, int indiceLinha, int indiceColuna) 
{              
    sheet.getRow(indiceLinha).getCell(indiceColuna).setCellType(HSSFCell.CELL_TYPE_STRING);
    if (sheet.getRow(indiceLinha).getCell(indiceColuna).getCellType() == HSSFCell.CELL_TYPE_STRING) {
        return sheet.getRow(indiceLinha).getCell(indiceColuna).getStringCellValue().trim();
    } else {
        return String.valueOf(sheet.getRow(indiceLinha).getCell(indiceColuna).getNumericCellValue());
    }
}
Was it helpful?

Solution

I guess that forcing cell type to HSSFCell.CELL_TYPE_STRING might be the reason of getting null.

A more robust way to obtain a string value from any type of cell (you might also have dates, formulas, etc.) is to use DataFormatter:

import org.apache.poi.ss.usermodel.DataFormatter;

static DataFormatter dataFormatter = new DataFormatter();

static String getStringValue(Cell cell) {
    return dataFormatter.formatCellValue(cell);
}

It is especially useful when you want to get exactly the same what is displayed in Excel (e.g numbers rounded to given decimal places).

OTHER TIPS

I have found in recent tests, that the method DateUtil.GetJavaDate(Double value) can throw a NullReferenceException for unknown reasons. This is the method NPOI uses to convert the numeric Excel date when calling cell.DateCellValue(). I recommend instead to use the method DateTime.FromOADate(cell.NumericCellValue) which seem to do the same conversion.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top