2016-08-03 98 views
-1

我有一個excel文件(test.xlsx),其中包含一列,稱爲id,其中我應用了一個公式,當我手動打開它時,所有id的值自動更改,因爲當我關閉它時,它會要求保存更改。如何在java中打開並保存excel文件

同我與Java代碼嘗試以下

public static void main(String[] args) { 

     String str1 = "c:/file/test.xlsx"; 
     try { 


      //open file 
      XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(new File(str1))); 
      System.out.println(wb.getSheetAt(0).getRow(1).getCell(0).getDateCellValue().toString()); 

      //save file 
      FileOutputStream out = new FileOutputStream(str1); 
      wb.write(out); 
      out.close(); 

      wb = new XSSFWorkbook(new FileInputStream(new File(str1))); 
      System.out.println(wb.getSheetAt(0).getRow(1).getCell(0).getDateCellValue().toString()); 

     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 

    } 




output: 
Thu Aug 04 01:08:34 IST 2016 
Thu Aug 04 01:08:34 IST 2016 

給出上面的代碼執行,我不讀文件與Apache POI的幫助下得到任何異常

我已經驗證後結果。

我想,在保存帶有代碼的文件後,新的id應該在Id列中,因爲它發生在手動打開和保存文件的情況下。

對我而言,它不適用於代碼。

請建議

如果你無法理解的問題,那麼像下面創建文件並打開它,然後手動關閉它,在這之後的代碼試試,你會明白的事情

enter image description here

+0

什麼是'exceldoc'?在代碼中沒有定義... –

+0

請定義「不工作」,並注意保存工作簿(使用POI)的方式與「wb.write(OutputStream)」類似,請參見https:// poi。 apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFWorkbook.html – 2016-08-03 18:09:30

+0

我編輯了我的問題 – vijendra

回答

1

我已經找到了解決辦法,在上面的代碼我要補充只有一條線,請檢查下面

public static void main(String[] args) { 

     String str1 = "c:/file/test.xlsx"; 
     try { 


      //open file 
      XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(new File(str1))); 
      System.out.println(wb.getSheetAt(0).getRow(1).getCell(0).getDateCellValue().toString()); 

      //FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); 

      XSSFFormulaEvaluator.evaluateAllFormulaCells(wb); 

      //save file 
      FileOutputStream out = new FileOutputStream(str1); 
      wb.write(out); 
      out.close(); 

      wb = new XSSFWorkbook(new FileInputStream(new File(str1))); 
      System.out.println(wb.getSheetAt(0).getRow(1).getCell(0).getDateCellValue().toString()); 

     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 

    }