Format number with thousands separator in Excel using Apache POI

两盒软妹~` 提交于 2019-12-21 11:34:33

问题


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 #,###,###?

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


回答1:


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

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:

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 #,###.




回答2:


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.



来源:https://stackoverflow.com/questions/27400825/format-number-with-thousands-separator-in-excel-using-apache-poi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!