How to get the formatted value of a number for a cell in Apache POI?

Tags: ,



I wanted to get the value of a Numeric cell as a simple string.

Suppose there the type of cell is numeric with value 90%. Now I cannot use cell.getStringCellValue() as it will throw exception. I also cannot use cell.getNumericCellValue() as it will return me .9 and not 90%.

I want to store in db which is of type varchar2, so I want the value in string only.

I cannot change the cell type in xls as its the end user job, I have to handle this in code itself.

Also formatter does’t work well as there could be different cell types in the xls…dd:mm,dd:mm:ss,formula etc.

All I want is that whatever the cell type is I need to get its value as simple String.

Answer

You can force the value to be returned as a String using the methods below

HSSFDataFormatter hdf = new HSSFDataFormatter();
System.out.println (hdf.formatCellValue(mycell));

will return “90%”

The API for this method is at http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/DataFormatter.html#formatCellValue%28org.apache.poi.ss.usermodel.Cell%29

This works directly even with an HSSFCell

it worked for me even when my Cell is an HSSFCell

i’ve also tried this cast – which works.

HSSFCell cell1 = (HSSFCell) row1.getCell(2);

HSSFDataFormatter hdf = new HSSFDataFormatter();
System.out.println ("formatted "+ hdf.formatCellValue(cell1));


Source: stackoverflow