Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Excel cell value in Numeric format using POI

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")
like image 494
omrid Avatar asked Jan 23 '12 06:01

omrid


People also ask

How do I change cell format in Apache POI?

To create date cell which display current date to the cell, we can use Apache POI's style feature to format the cell according to the date. The setDateformat() method is used to set date format.

Which is better XSSF or HSSF?

HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file format. XSSF is the POI Project's pure Java implementation of the Excel 2007 OOXML (. xlsx) file format. HSSF and XSSF provides ways to read spreadsheets create, modify, read and write XLS spreadsheets.


2 Answers

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)
like image 192
Abhijeet Rastogi Avatar answered Oct 18 '22 22:10

Abhijeet Rastogi


I used Big Decimal for this,

dCell.setCellValue(new BigDecimal("112.45").doubleValue());
like image 25
Kushan Avatar answered Oct 18 '22 22:10

Kushan