2017-07-17 106 views
0

如何在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; 
    } 
+1

因为过人之处单元格格 –

+0

Excel中使用十进制值的二进制表示,类似到Java的'double'。但是你可以将数字格式添加到单元格中。 –

+0

@PhilippSander如何摆脱单元格格式? –

回答

2

这是因为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. 写入xls而不是csv与Apache POI库(这里有一个例子),并用这些数字应用单元格格按上述代码段中
  2. 写入到CSV作为Strings,请在excel中打开它并为相应的列应用Text格式。
+0

了。getNetAmount是BigDecimal –

+0

行,工作簿无法解析 –

+0

这些仅仅是示例名称,您能分享写入xls的代码吗?我会相应地更新答案。 –

0

format your cell with this configuration

选择单元格并右键单击它,然后单击格式单元格,做这种配置则短声OK

+0

该程序将由别人运行,而不是在我的电脑上运行。 –