Your Search Bar For Shrewd Tips

How To Close Xssfworkbook In Java


Closing an XSSFWorkbook correctly is an essential part of working with Excel files in Java. An XSSFWorkbook represents an Excel workbook in the modern Office Open XML format, usually a file with an .xlsx extension. Because it can hold package files, streams, and other resources, leaving it open can cause resource leaks or make files difficult to replace. The safest approach is to close the workbook whenever you finish using it, even if an error occurs.

In most applications, Java’s try-with-resources statement is the simplest way to close an XSSFWorkbook. This guide explains how to close a workbook, how to handle input and output streams, and what to watch for when saving changes.

Why You Need to Close an XSSFWorkbook

An XSSFWorkbook is provided by Apache POI, a Java library for reading and writing Microsoft Office documents. The workbook uses an underlying Open Packaging Conventions (OPC) package to work with the parts of an .xlsx file. Closing the workbook releases the resources associated with that package.

If you do not close a workbook, your application may keep file handles or other resources open longer than necessary. Depending on the operating system and how the workbook was opened, this can prevent the source file from being renamed, replaced, or deleted. Repeatedly opening workbooks without closing them can also consume resources and cause problems in long-running applications.

Closing is not the same as saving. Calling close() releases resources; it does not write your latest changes to a file. To save changes, call write(OutputStream) before closing the workbook.

Close an XSSFWorkbook with Try-with-Resources

The recommended way to close an XSSFWorkbook is to declare it as a resource in a try-with-resources statement. Java automatically calls close() when execution leaves the block, whether the block completes normally or an exception is thrown.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadWorkbook {
    public static void main(String[] args) throws IOException {
        Path path = Path.of("report.xlsx");

        try (XSSFWorkbook workbook =
                     new XSSFWorkbook(Files.newInputStream(path))) {
            int sheetCount = workbook.getNumberOfSheets();
            System.out.println("Sheets: " + sheetCount);
        }
    }
}

This example demonstrates automatic workbook cleanup, but it is clearer and safer to manage the input stream as its own resource. The workbook and stream are separate objects, and managing both makes their lifecycles explicit.

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadWorkbook {
    public static void main(String[] args) throws Exception {
        Path path = Path.of("report.xlsx");

        try (InputStream input = Files.newInputStream(path);
             XSSFWorkbook workbook = new XSSFWorkbook(input)) {
            System.out.println(workbook.getSheetAt(0).getSheetName());
        }
    }
}

Resources are closed in the reverse order in which they are declared. In this example, Java closes the workbook first and the input stream second. If workbook creation or code inside the block fails, Java still attempts to close every resource that was successfully created.

Close an XSSFWorkbook After Writing an Excel File

When creating a new workbook, include both the workbook and the output stream in the try-with-resources statement. Write the workbook before the block ends. Java then closes the output stream and the workbook automatically.

import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class CreateWorkbook {
    public static void main(String[] args) throws Exception {
        Path path = Path.of("new-report.xlsx");

        try (XSSFWorkbook workbook = new XSSFWorkbook();
             OutputStream output = Files.newOutputStream(path)) {
            workbook.createSheet("Summary");
            workbook.write(output);
        }
    }
}

Here, workbook.write(output) writes the workbook contents to the destination. It does not replace the need to close the workbook. The output stream is also declared separately because the code that opens it is responsible for managing it.

Remember that resource closure happens at the end of the block. If you need to use the workbook again, do so before leaving that block. After it has been closed, do not continue reading from or writing to it.

Read, Modify, and Save an Existing Workbook

A common task is to open an existing spreadsheet, make changes, and save the result. Keep the workbook and its input stream open while you read or update the workbook, then write the result before the workbook is closed.

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class UpdateWorkbook {
    public static void main(String[] args) throws Exception {
        Path source = Path.of("source.xlsx");
        Path destination = Path.of("updated.xlsx");

        try (InputStream input = Files.newInputStream(source);
             XSSFWorkbook workbook = new XSSFWorkbook(input);
             OutputStream output = Files.newOutputStream(destination)) {

            workbook.createSheet("Notes");
            workbook.write(output);
        }
    }
}

This example writes to a separate destination file. Avoid opening the original file for output while it is still being used as the workbook’s input. Truncating or replacing the source while the package is open can lead to corrupted data or file-access problems. If you need to replace the original, write to a temporary file first, close all resources, and then replace the original using an appropriate file operation.

Close an XSSFWorkbook with a Finally Block

Try-with-resources is preferred in modern Java, but you may encounter older code that closes resources in a finally block. In that case, initialize the workbook to null, then check that it was created before closing it.

XSSFWorkbook workbook = null;

try {
    workbook = new XSSFWorkbook(inputStream);
    // Read or update the workbook.
} finally {
    if (workbook != null) {
        workbook.close();
    }
}

This pattern ensures that the workbook is closed even if an exception occurs after construction. However, it is easier to make mistakes with manual cleanup. For example, an exception thrown by close() can complicate the handling of an earlier exception. Try-with-resources manages these situations more consistently and should usually be your first choice.

Handle Exceptions When Closing a Workbook

The close() method can throw an IOException, so the surrounding code needs to handle or declare it. In the examples above, the methods declare an exception to keep the focus on resource management. In production code, you may want to catch the exception and provide useful context.

try (XSSFWorkbook workbook = new XSSFWorkbook()) {
    workbook.createSheet("Data");
    // Work with the workbook.
} catch (IOException e) {
    System.err.println("Could not create or close the workbook: "
            + e.getMessage());
    throw e;
}

With try-with-resources, Java calls close() even if an exception occurs in the block. If both the block and the closing operation fail, Java preserves the original exception and records the closing exception as a suppressed exception. This is one reason try-with-resources is generally safer than a simple manual finally block.

Common XSSFWorkbook Closing Mistakes

  • Assuming close saves changes: Call workbook.write(output) before closing if you need to save modifications.
  • Forgetting the output stream: Manage streams that your code opens, even when the workbook itself is also closed.
  • Closing too early: Do not close the workbook before you have finished reading, modifying, and writing it.
  • Using a closed workbook: After the resource block ends, treat the workbook as unavailable. Open it again if you need to continue working with the file.
  • Closing repeatedly: Close the workbook once at the end of its useful lifetime rather than calling close() throughout processing.
  • Writing over the open source: Prefer a separate output or temporary file when updating an existing workbook.

It is also useful to keep the workbook’s lifetime as short as practical. For example, avoid storing an open workbook in a long-lived field when a method can open it, process it, and close it locally. A clear resource scope makes cleanup easier to verify and reduces the chance of keeping file resources open accidentally.

Does Closing XSSFWorkbook Close the InputStream?

Do not rely on the workbook to manage every stream opened by your application. If your code creates an InputStream or OutputStream, declare it as a resource too. This makes ownership clear and ensures the stream is closed even if workbook construction or processing fails.

For example, declaring both an input stream and an XSSFWorkbook in the same try-with-resources statement is an explicit, dependable pattern. The same principle applies to output: close the stream that your code opened, and close the workbook after you finish using it.

Conclusion

To close an XSSFWorkbook in Java, use try-with-resources whenever possible. It automatically calls close() when your code leaves the resource block, including when an exception occurs. If you are saving changes, call workbook.write(output) before the block ends, and manage any input or output streams your code opens as separate resources.

Keeping workbook and stream lifetimes clear helps prevent resource leaks, file-locking issues, and accidental data loss. For most Apache POI applications, a short try-with-resources block is the cleanest way to read, modify, write, and close an Excel workbook safely.


Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.

Shrewdnia

Shrewdnia

Shrewdnia is a destination for curious minds seeking clarity, knowledge, and informed perspectives. Through insightful articles and practical guides our passionate team explores a wide range of topics designed to help readers understand the world around them, make smarter decisions, and stay informed in an ever-changing landscape.


💡 Every question sparks discovery, and every perspective enriches the conversation. Share your thoughts and insights in the comments 👇

Back to blog

Leave a comment

JOIN THE SHREWDNIA COMMUNITY FORUM

What do you think?

Have an opinion, experience, or question about this topic? Join the Shrewdnia Forum and share your thoughts with other readers.

Join the Forum →