在最后一位填充零

如何在excel文件的最后一位添加一个

我通过下面的代码打印下面的值

DecimalFormat df = new DecimalFormat("#.00"); System.out.println(s.getNetAmount()); System.out.println(df.format(s.getNetAmount())); 

结果是

 691.200 691.20 

但是,当我把它写入excel文件,我期望得到691.20 ,但我得到691.2。

这是我如何写入Excel文件

  public void write(List<? extends List> list) throws Exception { if (list != null) { try { writeFile(header(), detail(list.get(0))); } catch (BatchRunException ex) { throw new BatchRunException(" Fail..." + ex); } } } private void writeFile(String header, List<String> detail) throws IOException, BatchRunException { String fullPath = outputPath + fileNameFormat; File file = new File(fullPath); File path = new File(outputPath); if (!path.exists()) { path.mkdirs(); } if (!file.exists()) { file.createNewFile(); } try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) { bw.write(header); bw.write(NEW_LINE); for (String s : detail) { bw.write(s); bw.write(NEW_LINE); } } catch (IOException ex) { throw new BatchRunException(" Fail..." + ex); } } private String header() { StringBuilder bf = new StringBuilder(); bf.append("Employee Name").append(SEPERATOR); bf.append("Amount").append(SEPERATOR); return bf.toString(); } private List<String> detail(List<SettlementList> dList) { List<String> list = new ArrayList(); BigDecimal a = new BigDecimal("0"); for (SettlementList s : dList) { StringBuilder bf = new StringBuilder(); bf.append(s.Name()).append(SEPERATOR); bf.append(s.getNetAmount()).append(SEPERATOR); // here the error list.add(bf.toString()); } return list; } 

这是因为Cell风格而不是DecimalFormat 。 尝试设置单元格样式,例如:

 HSSFCell cell = row.createCell(0); HSSFCellStyle style = workbook.createCellStyle(); style.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00")); cell.setCellValue(s.getNetAmount().doubleValue()); 

更新

它看起来像你正在写入csv文件,并试图用XLS打开它。 在这种情况下,Excel将根据数据格式化单元格。 因此,对于像691.200这样的值的行,Excel将把它们解释为数字值并相应地进行格式化(使其成为691.2 )。 有两种方法来解决它:

  1. 使用Apache POI库(这里是一个示例)写入xls而不是csv ,并按照上面的代码片段应用单元格格式
  2. 用这些数字写入csv作为Strings ,在Excel中打开它,并为相应的列应用Text格式。

用这个配置格式化你的单元格

select你的单元格,然后右键单击它,然后单击格式单元格,然后执行此configuration,然后clik ok