Setting Excel cell value in Numeric format using POI

混江龙づ霸主 提交于 2019-12-05 11:44:41

问题


I want to store numeric data in excel sheet.
The numeric data is represented by String type in my java code.
Is it possible to set it as numeric without casting it?

I've tried the following code, but it wasn't converted to numeric type (I get a warning in excel saying that number is stored as text...)

HSSFCell dCell =...
dCell.setCellType(Cell.CELL_TYPE_NUMERIC);
dCell.setCellValue("112.45")

回答1:


You have to provide the value as a double. As the doc says:

setCellValue

public void setCellValue(double value)

set a numeric value for the cell

Parameters:

value - the numeric value to set this cell to. For formulas we'll set the precalculated value, for numerics we'll set its value. For other types we will change the cell to a numeric cell and set its value.

So, it should be

dCell.setCellValue(new Double("123"));

OR

dCell.setCellValue(123);  //Remember, the way you did was, you actually passed a string (no quotes)



回答2:


I used Big Decimal for this,

dCell.setCellValue(new BigDecimal("112.45").doubleValue());



回答3:


Try to use wrapper classes:

dCell.setCellValue(new Double(112.45));

BTW, it will work if you simply give the value instead of the double cotes as follows:

dCell.setCellValue(112.45);



回答4:


Old one But Still it This will help Some one from .NET who use NPOI

dCell.setCellValue(Convert.ToDouble(112.45));

We do have

cell.SetCellType(NPOI.SS.UserModel.CellType.NUMERIC); 

which doesn't remove the warning but the 1st code did worked after converting to Double for All integers and Double values in .net



来源:https://stackoverflow.com/questions/8967942/setting-excel-cell-value-in-numeric-format-using-poi

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