15

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")
omrid
  • 497
  • 3
  • 10
  • 20
  • Isn't the setCellValue method overloaded to support other types, i.e. can't you pass a float or something into that method? You are currently passing a string. – mydoghasworms Jan 23 '12 at 06:31
  • Yes, I can pass any type. I asked if its possible to pass value AS String and auto-convert it to the needed type. – omrid Jan 23 '12 at 06:40
  • see this: [enter link description here][1] [1]: http://stackoverflow.com/questions/5335285/write-number-in-excel-cell-with-poi – John Ding Jun 10 '14 at 13:57

4 Answers4

26

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)
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
shadyabhi
  • 16,675
  • 26
  • 80
  • 131
  • 1
    so I must set value in the needed type? it can't be "auto-converted" from String? – omrid Jan 23 '12 at 06:39
  • 2
    No, simply use what I said or dCell.setCellValue(123). Remember, no quotes or it will make it a string. (which you actually did) – shadyabhi Jan 23 '12 at 06:40
8

I used Big Decimal for this,

dCell.setCellValue(new BigDecimal("112.45").doubleValue());
Kushan
  • 10,657
  • 4
  • 37
  • 41
2

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);
Arun
  • 2,562
  • 6
  • 25
  • 43
1

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

Peru
  • 2,871
  • 5
  • 37
  • 66