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

荒凉一梦 提交于 2019-12-19 09:04:34

问题


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.


回答1:


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));



回答2:


Try

cell.getRichStringCellValue ().getString();    

Have a look at this example
Here is Doc



来源:https://stackoverflow.com/questions/3819633/how-to-get-the-formatted-value-of-a-number-for-a-cell-in-apache-poi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!