21

I am using poi 3.6

I am able to create the excel properly. But when I trying to set the cell type as number , it always give me cell type as general.

i.e. In the newly create excel , when I right click and go to format cell ->there I always found number to be a General.

My code is like this

style.setAlignment(CellStyle.ALIGN_RIGHT);
dataCell.setCellValue(Float.parseFloat(value as String);
dataCell.setCellType(Cell.CELL_TYPE_NUMERIC);
dataCell.setCellStyle(style);

Can you please suggest what is missing here ?

Anup
  • 405
  • 2
  • 10
  • 26

2 Answers2

32

You can try this approach too:

HSSFRow row = sheet.createRow(sheet.getLastRowNum());
HSSFCell cell = row.createCell(0);
HSSFCellStyle style = workbook.createCellStyle();
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
cell.setCellStyle(style);
cell.setCellValue(Float.parseFloat("21.5"));

Of course, take a look at the documentation and examples about data formats.

Dani
  • 3,744
  • 4
  • 27
  • 35
  • Thanks a lot It is working for me I have tried //style.setDataFormat(format.getFormat("0.0")); but it didnt work .. Thanks a lot – Anup Mar 06 '13 at 13:33
-1

The method you are looking for is called "setNumericCellValue" if I'm not mistaken. Also, try setting the cell type before setting the value.

Sebastian
  • 5,177
  • 4
  • 30
  • 47
  • 1
    There is no method setNumericCellValue. There is only a getNumericCellValue. The doc for that at https://poi.apache.org/apidocs/dev/org/apache/poi/xssf/usermodel/XSSFCell.html has a reference that implies the format can be applied, but not the type. – Fred Andrews Nov 19 '19 at 19:34
  • Thanks for the downvote after more than 10 years... The API might have changed in there meantime. – Sebastian Aug 28 '23 at 14:07