Java – in Apache POI 3.7, double values are written in numeric cells in a specific format

I need to write a double value in a numeric cell in a specific format. I mean, the generated XLS must have a numeric cell containing the double value, such as 8,1 I'm trying something like:

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

However, since the format method returns a string, they are always represented as text cells whether or not cells are created I was thinking about two options:

>Force cells as numeric cells. > Forget decimalformat and use the double class to specify a comma as the decimal separator. I didn't know it was possible

Any ideas?

Solution

I may be missing something, but I think you just need to style the cells using formatting rules to display a 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);

This creates a formatting rule, creates a cell, sets the cell to a value of 8.1, and then styles it

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>