从现有 Excel 文件编辑会删除其数据

Editting from an existing Excel file deletes its data

为什么我的 Excel 工作簿中的工作表在我通过 FileOutStream 写入 to/edit 时被删除?

代码:

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();

您的问题不在于 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/