Apache POI 格式化 Excel 文件中的双精度数字



我正在使用apache-poi来创建一些报告。我对小数点分隔符有问题。现在我在 excel 文件中显示了以下内容:

对于 111.2343 -> 111.23

对于 111.23 -> 111.23

对于 111.2 -> 111.2

对于 111 -> 111.(见末尾的点)

问题出在 111 号码上。我不想看到尾随的点(或逗号,取决于语言)。

这是我当前用于格式化单元格的代码。这可以使用apache-poi来实现吗?

谢谢

尤利安

PS:有没有办法在poi中使用java.text.Format?我看到这有DecimalFormat setDecimalSeparatorAlwaysShowed方法,它可以做我想要的。

private void createColumnStyle(XSSFSheet sheet, int maxRows,int col)
{
    XSSFWorkbook wb = sheet.getWorkbook();
    XSSFFont font = wb.createFont();
    font.setFontHeightInPoints((short)10);
    font.setFontName("Calibri");
    XSSFCellStyle colStyle = wb.createCellStyle();  
    colStyle.setFont(font);                
    colStyle.setAlignment(HorizontalAlignment.RIGHT);
    colStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
    colStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
    colStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
    colStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
    CreationHelper createHelper = wb.getCreationHelper();                   
    colStyle.setDataFormat(createHelper.createDataFormat().getFormat("#,##0.##"));

    for (int i=3; i<maxRows; i++ )
    {
        XSSFCell cell = sheet.getRow(i).createCell(col);
        cell.setCellStyle(colStyle);
    }
}

使用 DecimalFormat 适用于所有情况:

DecimalFormat dec = new DecimalFormat("#.00");
double cellValue = Double.valueOf(dec.format(111));
XSSFCell cell = sheet.createRow(0).createCell(0);
cell.setCellValue(cellValue);

这会将单元格值设置为"仅111"。

最新更新