Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write Double value in numeric cell with specific format in Apache Poi 3.7

I need to write a Double value in a numeric cell using a specific format, i mean, the generated xls must have numeric cells containing Double values like, for example: 8,1. I am trying something like:

DecimalFormat dFormat = new DecimalFormat("##.#");
dFormat.format(doubleValue);

But, since format method returns a String, no matter whether I create cells as numeric or not, they always behave as text cells. I was thinking about two options:

  • Forcing cells to behave as numeric cells.
  • Forgetting about DecimalFormat and use Double class specifying comma as the decimal separator, what i'm not sure it's possible.

Any idea?

like image 581
Dani Avatar asked Mar 20 '12 15:03

Dani


People also ask

Which method is used to get the format of the particular cell in Apache POI?

Class DataFormatter. DataFormatter contains methods for formatting the value stored in a Cell. This can be useful for reports and GUI presentations when you need to display data exactly as it appears in Excel. Supported formats include currency, SSN, percentages, decimals, dates, phone numbers, zip codes, etc.

How do I change the date format in Excel 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. Lets see an example in which we are creating a cell containing current date.


1 Answers

I may be missing something, but I think you just want to style the cell with a format rule to display a single decimal place

// Do this only once per file
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(
    wb.getCreationHelper().createDataFormat().getFormat("#.#"));

// Create the cell
Cell c = row.createCell(2);
c.setCellValue(8.1);
c.setCellStyle(cellStyle);

That will create a formatting rule, create a cell, set the cell to be the value 8.1, then style it

like image 57
Gagravarr Avatar answered Nov 15 '22 13:11

Gagravarr