To write to an Excel file in Java, the most reliable and industry-standard method is using the Apache POI library. This library provides the necessary APIs to create, modify, and save files in the .xls (HSSF) and .xlsx (XSSF) formats by treating the spreadsheet as a hierarchy of Workbooks, Sheets, Rows, and Cells. Because Java does not have a built-in native library for Microsoft Office formats, Apache POI acts as the bridge that translates Java objects into the XML-based structures required by modern Excel files.
What You'll Need
- Java Development Kit (JDK): Version 8 or higher is recommended to ensure compatibility with the latest POI releases.
- Integrated Development Environment (IDE): IntelliJ IDEA, Eclipse, or VS Code for managing project dependencies.
- Build Tool: Maven or Gradle to handle the Apache POI dependencies and their transitive requirements (such as POI-OOXML).
- Apache POI Libraries: Specifically
poiandpoi-ooxmlfor .xlsx support.
Step-by-Step
- Add Dependencies to Your Project: If you are using Maven, add the following dependencies to your
pom.xml. You need both the core POI library and the OOXML library to handle the modern .xlsx format. Ensure the versions match to avoidClassNotFoundExceptionerrors. For Maven, addorg.apache.poi:poiandorg.apache.poi:poi-ooxml. If using Gradle, use theimplementationconfiguration for both. - Initialize the Workbook: The Workbook is the top-level object representing the entire Excel file. To create a modern .xlsx file, instantiate an
XSSFWorkbook. For the older .xls format, useHSSFWorkbook. TheXSSFWorkbookis preferred for larger datasets as it supports the Open XML standard. - Create a Sheet: A workbook can contain multiple sheets. Use the
createSheet("SheetName")method on your workbook object. This creates a blank tab at the bottom of the Excel file. It is important to name your sheet clearly, as this is what the end-user will see. - Create a Row: Data in Excel is organized by rows. Use
sheet.createRow(int rowNum). Note that row indices are zero-based, meaning the first row of the spreadsheet is index 0. If you are creating a header row, start with 0; for the first line of data, use 1. - Create and Populate Cells: Within each row, you must create individual cells using
row.createCell(int colNum). Like rows, columns are zero-based. Once a cell is created, use thesetCellValue()method to add data. Apache POI provides overloaded versions of this method to handleString,double,boolean, andDatetypes. - Apply Styling (Optional but Recommended): To make the file professional, create a
CellStyleobject usingworkbook.createCellStyle(). You can set fonts to bold for headers, add borders, or align text. Apply the style to the cell usingcell.setCellStyle(style). Be cautious not to create a new style object inside a loop, as Excel has a limit on the number of unique styles per workbook; create the style once and reuse it. - Write the Workbook to a File: The data currently exists only in your computer's RAM. To save it to the disk, use a
FileOutputStream. Wrap theworkbook.write(outputStream)call in a try-with-resources block to ensure the stream is closed properly, preventing memory leaks and file locking issues. - Close the Workbook: Finally, call
workbook.close(). This releases the resources associated with the workbook object and ensures that the file is fully flushed to the storage device.
Common Mistakes
One of the most frequent errors is the Style Overflow. Developers often create a new CellStyle object inside a for loop while iterating through thousands of rows. Because Excel limits the total number of unique styles, this will eventually crash the application or corrupt the resulting file. Always define your styles at the top of your method and reference the same object for every cell that requires that specific look.
Another common mistake is Incorrect Indexing. Because Java uses zero-based indexing, developers sometimes forget that createRow(1) actually creates the second row. This often leads to a blank first row in the exported file. Always double-check your loop counters when mapping a List or Array to an Excel sheet.
Resource Leaks are also prevalent. Failing to close the FileOutputStream or the XSSFWorkbook can lead to "File in use" errors when you try to open the file in Excel immediately after the program runs. Using try-with-resources is the standard way to prevent this in modern Java.
Lastly, developers often confuse HSSFWorkbook and XSSFWorkbook. Using HSSFWorkbook for a file named .xlsx will result in a corrupted file that Excel cannot open because the internal binary structure does not match the file extension.
Tips
For very large datasets (tens of thousands of rows), XSSFWorkbook can consume a massive amount of heap memory because it keeps the entire document model in RAM. In these cases, use SXSSFWorkbook (Streaming XML Spreadsheet Workbook). This class writes data to temporary files on the disk instead of keeping everything in memory, which prevents OutOfMemoryError.
To improve readability, use sheet.autoSizeColumn(int colIndex). This method calculates the width of the longest piece of data in a column and adjusts the column width automatically. However, be aware that autoSizeColumn can be computationally expensive for very large sheets, so it is best to call it once at the end of the process.
When dealing with numeric data that should look like currency or percentages, do not simply concatenate a symbol to a string (e.g., "$10.00"). Instead, set the cell value as a double and use a DataFormat object to apply a currency mask. This allows the user to perform calculations on the cells within Excel.
Troubleshooting
If you encounter a ClassNotFoundException or NoClassDefFoundError related to xmlbeans or poi-ooxml-schemas, it means your classpath is missing required transitive dependencies. If you are using Maven, run mvn clean install to refresh dependencies. If you are adding JARs manually, ensure you have included all the necessary support libraries found in the Apache POI download package.
If the resulting Excel file is reported as "Corrupt" when opened, check two things first: ensure the FileOutputStream was properly closed and that you used the correct Workbook class for the file extension. A common cause of corruption is calling workbook.write() but forgetting to close the stream, leaving the file trailing or incomplete.
If your application crashes with an OutOfMemoryError, check the size of your dataset. If you are processing more than 10,000 rows, switch from XSSFWorkbook to SXSSFWorkbook. You will need to specify a window size (e.g., 100 rows) which determines how many rows are kept in memory before being flushed to disk.
If autoSizeColumn is not working as expected, ensure you call it after all the data has been written to the sheet. If you call it while the sheet is still empty or partially filled, it cannot accurately calculate the required width for the final data set.
Frequently Asked Questions
Can I write to an existing Excel file instead of creating a new one?
Yes. Instead of instantiating a new workbook, use WorkbookFactory.create(new File("path/to/file.xlsx")). This opens the existing file, allowing you to retrieve existing sheets or add new rows to them before saving the changes back to the file.
Which is better: .xls or .xlsx?
The .xlsx format (XSSF) is superior. It supports more rows (over 1 million vs 65,536), more columns, and uses a compressed XML format that generally results in smaller file sizes and better data integrity.
Do I need Microsoft Excel installed on the server to use Apache POI?
No. Apache POI is a pure Java library that manipulates the file structure directly. It does not require any installation of Microsoft Office or any proprietary drivers to create or read Excel files.
How do I handle special characters or different languages?
Apache POI handles Unicode by default. As long as your Java source files are saved in UTF-8 and you are using setCellValue(String), special characters and non-English scripts will be preserved correctly in the Excel file.
Can I add formulas to cells using Java?
Yes. Use cell.setCellFormula("SUM(A1:A10)"). This inserts the formula into the cell. Note that the formula result is calculated by Excel when the file is opened, not by the Java library itself.