2017-07-17 99 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

該程序將由別人運行,而不是在我的電腦上運行。 –