为什么我通过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,它将重写该流中的工作簿,而不管它是否为新文件。 –