2015-10-19 64 views
0

爲什麼我通過FileOutStream寫入/編輯Excel工作簿中的工作表時會被刪除?從現有Excel文件編輯刪除其數據

代碼:

HSSFWorkbook workbook; 
FileOutputStream fileOut = null; 

String excelFileName = util.getFile(FileExtension.XLS); // Here is a method I wrote in a utility class I made, that asks if they want to create a new file or select an existing one. 
// This works. And it returns the location of the file created/selected. 

fileOut = new FileOutputStream(excelFileName); 
workbook = new HSSFWorkbook(); 
getAllSheetsFromWB(workbook); 

workbook.write(fileOut); 
workbook.close(); 
fileOut.close(); 

在這裏,我試圖讓所有的表,所以我能確定是否有在工作簿上的任何現有的表:

private String[] getAllSheetsFromWB(HSSFWorkbook workbook) { 
    int numSheets = workbook.getNumberOfSheets(); 
    String[] result = new String[numSheets]; 

    result = new String[numSheets]; 

    if(numSheets > 0) { 
     for (int i = 0; i < numSheets; i++) { 
      result[i] = workbook.getSheetAt(i).getSheetName(); 
     } 
    } 

    return result; 
} 

這樣做刪除表在現有的工作簿上。

更新:這是因爲我從來沒有使用FileInputStream來讀取文件。見下面的解決方案。

HSSFWorkbook workbook = null; 
FileOutputStream fileOut = null; 
FileInputStream fileIn = null; 

fileIn = new FileInputStream((new File(excelFileName)); 
workbook = new HSSFWorkbook(fileIn); 

//do stuff to workbook here 

fileOut = new FileOutputStream(excelFileName); 

workbook.write(fileOut); 
workbook.close(); 
fileIn.close(); 
fileOut.close(); 
+0

這取決於你用來使用excel文件的庫。在POI中,這相對容易。 –

+0

我正在使用Apache POI。如果我創建一個新的,在寫入之前是否必須關閉它? – PuggyLongLegs

+0

在POI中,您只需傳遞一個OutputStream,它將重寫該流中的工作簿,而不管它是否爲新文件。 –

回答

1

你的問題不是getAllSheetsFromWB,而是你從來沒有讀過excel文件。

FileInputStream file = new FileInputStream(excelFileName); 

//Get the workbook instance for XLS file 
HSSFWorkbook workbook = new HSSFWorkbook(file); 

因此你在那裏創建一個new HSSFWorkbook(),寫這個空工作簿文件前workbook.write(fileOut);

當然,你也應該做一些try catchclose

欲瞭解更多信息請查看本java-read-write-excel-file-apache-poi/

+0

非常感謝。有效。 – PuggyLongLegs

+0

我的榮幸,考慮接受答案並結束問題,玩得開心 –