爲什麼我通過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();
這取決於你用來使用excel文件的庫。在POI中,這相對容易。 –
我正在使用Apache POI。如果我創建一個新的,在寫入之前是否必須關閉它? – PuggyLongLegs
在POI中,您只需傳遞一個OutputStream,它將重寫該流中的工作簿,而不管它是否爲新文件。 –