2015-10-19 27 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

我的荣幸,考虑接受答案并结束问题,玩得开心 –