繁体   English   中英

始终使用Apache poi在excel单元格中显示两个小数点

[英]Always show two decimal points in excel cells using Apache poi

例如,

XSSFCellStyle style=(XSSFCellStyle) workbook.createCellStyle();
style.setDataFormat(workbook.createDataFormat().getFormat("#.##"));

productCell.setCellValue(12.4);
productCell.setCellType(Cell.CELL_TYPE_NUMERIC);
productCell.setCellStyle(style);

这在指定的单元格中显示12.4 它应该是12.40 12显示为12.这是非常不必要的。

如果该值为0 ,则显示一个点. 它应始终显示两个十进制数字 - 0.00 ,在这种情况下,无论存储在单元格中的值如何。

如何强制excel始终在数字单元格中显示两位小数?


我使用以下样式之一来显示数字单元格。

XSSFColor commonColor = new XSSFColor(new java.awt.Color(240, 240, 240));
XSSFColor cellBorderColour = new XSSFColor(new java.awt.Color(0, 76, 153));

Font font = workbook.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
font.setColor(IndexedColors.DARK_BLUE.index);

XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle();
style.setFillForegroundColor(commonColor);
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setAlignment(CellStyle.ALIGN_RIGHT);
style.setFont(font);

style.setBorderLeft(BorderStyle.HAIR);
style.setBorderColor(XSSFCellBorder.BorderSide.LEFT, cellBorderColour);
style.setBorderTop(BorderStyle.HAIR);
style.setBorderColor(XSSFCellBorder.BorderSide.TOP, cellBorderColour);
style.setBorderRight(BorderStyle.HAIR);
style.setBorderColor(XSSFCellBorder.BorderSide.RIGHT, cellBorderColour);
style.setBorderBottom(BorderStyle.DOUBLE);
style.setBottomBorderColor(cellBorderColour);

我应用了一些excel公式来对数字单元格执行一些计算,这些数字单元格应该在数字单元格上应用数字格式(向上舍入一半)之后执行。

在Excel格式化中, #表示“仅在需要时将数字放在此处”,但0表示“始终在此处放置数字,即使它是不必要的0”。 您可以在Apache POI中指定数据格式, 就像在Excel本身中一样 如果要显示0位数,则需要使用0 s作为格式化数字。 尝试

style.setDataFormat(workbook.createDataFormat().getFormat("0.00"));

这将使值0显示为0.00 ,将12.412.40

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM