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

时间:2015-10-19 19:53:23

标签: java apache-poi

为什么每次通过FileOutStream写入/编辑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();

1 个答案:

答案 0 :(得分: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);之前

当然,您还应该对流{/ 1}}和try catch做一些

有关详细信息,请查看此java-read-write-excel-file-apache-poi/