Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Apache poi's Workbook.close() method write content to input file?

Apache poi's documentation (version 3.17) says

void close()

throws java.io.IOException

Close the underlying input resource (File or Stream), from which the Workbook was read.

My code creates a workbook from a template file, does something with it and writes it to a new file. The template file should be left unchanged. But when I call the close() method, the file is changed in the same way as the output file.

Can someone explain this? Is there something like a built-in write() call in the close() method? Is this a bug or a feature?

My solution so far is to just leave away the close() call, but it feels incomplete somehow.

    String inPath = "/home/elmicha/test/template.xlsx";
    String outPath = "/home/elmicha/test/out.xlsx";

    try {
        Workbook xlsxFile = WorkbookFactory.create(new File(inPath));

        xlsxFile.getSheetAt(0).createRow(0).createCell(0).setCellValue("test");

        try (FileOutputStream pOuts = new FileOutputStream(outPath)) {
            xlsxFile.write(pOuts);
            
        xlsxFile.close();
        
        }

    } catch (IOException | InvalidFormatException | EncryptedDocumentException ex) {
        //...
    }
like image 248
JosefScript Avatar asked Sep 09 '26 07:09

JosefScript


1 Answers

That's quite unusual. I don't see why the template file would be written to. It certainly wasn't my experience. You can try:

  • Using FileInputStream instead of File to make it impossible to write to the template file.
  • Using try-with-resources to automatically close Workbook.

Here's an example:

String inPath = "/home/elmicha/test/template.xlsx";
String outPath = "/home/elmicha/test/out.xlsx";

try (Workbook xlsxFile = WorkbookFactory.create(new FileInputStream(inPath))) {
    xlsxFile.getSheetAt(0).createRow(0).createCell(0).setCellValue("test");

    try (FileOutputStream pOuts = new FileOutputStream(outPath)) {
        xlsxFile.write(pOuts);
    }

} catch (IOException | InvalidFormatException | EncryptedDocumentException ex) {
    //...
}

Or perhaps:

String inPath = "/home/elmicha/test/template.xlsx";
String outPath = "/home/elmicha/test/out.xlsx";

try (Workbook xlsxFile = WorkbookFactory.create(new FileInputStream(inPath));
    FileOutputStream pOuts = new FileOutputStream(outPath)) {

    xlsxFile.getSheetAt(0).createRow(0).createCell(0).setCellValue("test");
    xlsxFile.write(pOuts);


} catch (IOException | InvalidFormatException | EncryptedDocumentException ex) {
    //...
}
like image 102
Emmanuel Rosa Avatar answered Sep 10 '26 20:09

Emmanuel Rosa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!