我想使用Apache POI读取现有的xlsx文件,对其进行一些添加并将更改的文件保存到新位置 .

但是,我注意到,在保存文件的过程中,POI也会覆盖现有的excel . 有没有办法避免这种情况?

这是我用来打开工作簿的函数:

public static Workbook openWorkbook(File excelFile) throws ETLException {
        try {
            return WorkbookFactory.create(excelFile);
        } catch (IOException | InvalidFormatException e) {
            ETLInterfaceLogger.getLogger().error("Cannot open Excel file");
            throw new ETLException("Error opening excel file: " + e.getMessage());
        }
    }

这是我用来将更改的文件写入磁盘的函数:

public void writeWorkbook(File outputPath) throws ETLException {
        FileOutputStream stream = null;
        try {
            stream = new FileOutputStream(outputPath);
            workbook.write(stream);
            stream.close();
            workbook.close();
        } catch (IOException e) {
            throw new ETLException("Error writing XLSX to disk: " + e.getMessage());
        } finally {
            if (stream != null)
                try {
                    stream.close();
                } catch (IOException e) {
                    ETLInterfaceLogger.getLogger().error("Cannot close outputstream: " + e.getMessage());
                }
        }
    }

即使FileOutputStream在不同的文件上打开,POI仍会覆盖原始文件以及写入outputPath指定的位置 .

有没有办法阻止它这样做?