本文介绍了在 Apache Poi 3.7 中以特定格式在数字单元格中写入 Double 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用特定格式在数字单元格中写入一个 Double 值,我的意思是,生成的 xls 必须包含包含 Double 值的数字单元格,例如:8,1.我正在尝试类似的东西:

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:

  • 强制单元格表现为数字单元格.
  • 忘记 DecimalFormat 并使用 Double 类指定逗号作为小数点分隔符,我不确定这是否可行.

有什么想法吗?

推荐答案

我可能遗漏了一些东西,但我认为您只想使用格式规则设置单元格样式以显示单个小数位

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);

这将创建一个格式规则,创建一个单元格,将单元格设置为值 8.1,然后设置样式

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

这篇关于在 Apache Poi 3.7 中以特定格式在数字单元格中写入 Double 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 11:57