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
更新
2 个解决方案
#1
7
Just #,###
or #,##0
should 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将其解释为每三个数字有数千个分隔符(不仅仅是在最后三个数字之前,我推断它是你所期望的)。
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分隔符:
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 #,###
.
单击“确定”,然后重新打开数字格式对话框并转到“自定义”。看一下格式化代码(“Type”)。它说#,## 0,对我来说给出与#,###完全相同的结果。
#2
5
Just add this:
只需添加:
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00"));
and it will follow the format you want.You can refer this link to get more format setting.
它将遵循您想要的格式。您可以参考此链接以获取更多格式设置。
#1
7
Just #,###
or #,##0
should 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将其解释为每三个数字有数千个分隔符(不仅仅是在最后三个数字之前,我推断它是你所期望的)。
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分隔符:
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 #,###
.
单击“确定”,然后重新打开数字格式对话框并转到“自定义”。看一下格式化代码(“Type”)。它说#,## 0,对我来说给出与#,###完全相同的结果。
#2
5
Just add this:
只需添加:
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00"));
and it will follow the format you want.You can refer this link to get more format setting.
它将遵循您想要的格式。您可以参考此链接以获取更多格式设置。