Java 使用 Apache POI 在 Excel 中使用千位分隔符格式化数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27400825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:17:34  来源:igfitidea点击:

Format number with thousands separator in Excel using Apache POI

javaexcelformattingapache-poi

提问by Alkis Kalogeris

I want to format some number cells, with a comma as thousands separator. For example:

我想格式化一些数字单元格,用逗号作为千位分隔符。例如:

12        -> 12
1200      -> 1,200
12000     -> 12,000
12000000  -> 12,000,000
120000000 -> 120,000,000

I have the following code. What should I use as formatStr? Is there an easy way? Or do I have to detect the number of zeros in order to produce something like this #,###,###?

我有以下代码。我应该用formatStr什么?有没有简单的方法?或者我是否必须检测零的数量才能产生这样的东西#,###,###

String formatStr = "";
HSSFCellStyle style = workbook.createCellStyle();
HSSFDataFormat format = workbook.createDataFormat();
style.setDataFormat(format.getFormat(formatStr));
cell.setCellStyle(style);
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);

Keep in mind that I'm dealing with numbers. The cell type will be numeric, not string.

请记住,我正在处理数字。单元格类型将为数字,而不是字符串。

Update

更新

enter image description here

在此处输入图片说明

采纳答案by Jean-Fran?ois Corbett

Just #,###or #,##0should be sufficient. Excel interprets this as having thousands separators every three digits (not just before the last three, which I infer is what you were expecting).

刚好#,####,##0应该足够了。Excel 将此解释为每三位数字有数千个分隔符(不仅仅是在最后三位之前,我推断这是您所期望的)。

enter image description here

在此处输入图片说明

In the spirit of teaching a man to fish, this is how you can find out for yourself:

本着教人钓鱼的精神,您可以通过以下方式亲自了解:

Format as Number, 0 decimal places, with 1000 separator:

格式为数字,0 位小数,1000 分隔符:

enter image description here

在此处输入图片说明

Click OK, then re-open the number format dialog and go to Custom. Have a look at the formatting code ("Type"). It says #,##0, which for me gives the exact same result as #,###.

单击确定,然后重新打开数字格式对话框并转到自定义。看看格式代码(“类型”)。它说#,##0,这对我来说给出的结果与#,###.

enter image description here

在此处输入图片说明

回答by Ian

Just add this:

只需添加这个:

style.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00"));

and it will follow the format you want.You can refer this linkto get more format setting.

它将遵循您想要的格式。您可以参考此链接以获取更多格式设置。