To read and write Excel files in Java, use Apache POI: add the poi and poi-ooxml dependencies to your build, open a workbook with XSSFWorkbook (for .xlsx) or HSSFWorkbook (for .xls), then use getSheet, getRow, getCell to read and createRow, createCell, setCellValue to write. Close the workbook in a try-with-resources block so file handles are released. The steps below cover setup, reading, writing, and the mistakes that cause the most failed runs.
What You'll Need
- Java 8 or newer installed, with
JAVA_HOMEset andjavacon your PATH. - A build tool: Maven or Gradle (both shown below). If you use neither, you can add the POI JARs manually, but dependency management is far easier.
- An IDE or editor (IntelliJ IDEA, Eclipse, VS Code with the Java extension, or a plain terminal).
- An existing .xlsx or .xls file if you want to read one; for writing, POI creates the file for you.
Step-by-Step
- Create a project and add Apache POI. In Maven, add to
pom.xmlinside<dependencies>:<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>5.2.5</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.5</version> </dependency>
In Gradle:implementation 'org.apache.poi:poi:5.2.5'andimplementation 'org.apache.poi:poi-ooxml:5.2.5'. Check Maven Central for the current version; the numbers above are a working baseline.poi-ooxmlpulls in the XMLBeans and OOXML schema libraries that .xlsx needs, so do not omit it. - Import the classes you need. At the top of your Java file:
import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.*;
org.apache.poi.ss.usermodelholds the interfaces (Workbook,Sheet,Row,Cell) that work for both formats; the concrete classes (XSSFWorkbook,HSSFWorkbook) live in their own packages. - Read an existing workbook. Open the file with a
FileInputStreamand wrap it inXSSFWorkbookfor .xlsx. Iterate rows and cells:try (FileInputStream fis = new FileInputStream("data.xlsx"); Workbook wb = new XSSFWorkbook(fis)) { Sheet sheet = wb.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) { switch (cell.getCellType()) { case STRING: System.out.print(cell.getStringCellValue() + "\t"); break; case NUMERIC: System.out.print(cell.getNumericCellValue() + "\t"); break; case BOOLEAN: System.out.print(cell.getBooleanCellValue() + "\t"); break; case FORMULA: System.out.print(cell.getCellFormula() + "\t"); break; default: System.out.print("\t"); } } System.out.println(); } }Always checkgetCellType()before calling a getter; callinggetStringCellValue()on a numeric cell throwsIllegalStateException. - Write a new workbook. Create a workbook, a sheet, rows, and cells, then write to an
OutputStream:try (Workbook wb = new XSSFWorkbook(); FileOutputStream fos = new FileOutputStream("out.xlsx")) { Sheet sheet = wb.createSheet("Report"); Row header = sheet.createRow(0); header.createCell(0).setCellValue("Name"); header.createCell(1).setCellValue("Score"); Row data = sheet.createRow(1); data.createCell(0).setCellValue("Alice"); data.createCell(1).setCellValue(42.5); wb.write(fos); }Thetry-with-resourcesblock closes both the workbook and the stream, which flushes the data. - Update an existing file. Read it into a
Workbook, modify cells, then write it back to a different file path first to verify, and only then overwrite the original:try (FileInputStream fis = new FileInputStream("data.xlsx"); Workbook wb = new XSSFWorkbook(fis)) { Sheet sheet = wb.getSheetAt(0); Row row = sheet.getRow(1); if (row == null) row = sheet.createRow(1); Cell cell = row.getCell(2); if (cell == null) cell = row.createCell(2); cell.setCellValue("Updated"); try (FileOutputStream fos = new FileOutputStream("data-updated.xlsx")) { wb.write(fos); } }Rows and cells can be null in sparse sheets, so guard with null checks before writing. - Handle both .xls and .xlsx. Use
WorkbookFactory.create(file)orWorkbookFactory.create(inputStream)and let POI pick the right implementation based on the file header. This avoids hard-codingXSSFWorkbookand failing on older .xls files. - Format numbers and dates if needed. Create a
CellStylefrom the workbook (wb.createCellStyle()), set a data format withstyle.setDataFormat(wb.createDataFormat().getFormat("0.00"))or a date format like"yyyy-mm-dd", and apply it withcell.setCellStyle(style). Reuse styles across cells; creating one per cell bloats the file. - Run and verify. Compile and run from your IDE or with
mvn exec:java/gradle run. Open the output file in Excel or LibreOffice to confirm values and formatting. If the file opens with a repair prompt, the write was likely interrupted or the stream was not closed.
Common Mistakes
- Missing
poi-ooxml. Only addingpoicausesNoClassDefFoundErrorfor OOXML classes when you open .xlsx files. - Calling the wrong cell getter. Numeric cells need
getNumericCellValue(); strings needgetStringCellValue(). Check the type first. - Ignoring null rows and cells. Excel sheets are sparse; a row may exist without a cell at the index you expect.
- Not closing the workbook. On Windows this locks the file and blocks later writes; on any OS it can leave the output truncated.
- Writing to the same file you are reading. Open the input stream, read, close it, then open the output stream. Do not write to a file that is still open for reading.
- Using
HSSFWorkbookfor .xlsx. That class handles the legacy .xls format; it will fail or corrupt modern files. - Forgetting that formulas are not recalculated. POI writes formulas but does not evaluate them; Excel calculates on open. Read cached values with
getNumericCellValue()after a formula cell has been evaluated by Excel, or useFormulaEvaluatorif you need values without opening Excel.
Tips
- Use
WorkbookFactory.createwhen the input format is unknown; it detects .xls vs .xlsx automatically. - For large files, use the streaming API (
SXSSFWorkbookfor writing,XSSFReaderfor reading) to keep memory low. The standardXSSFWorkbookloads the whole file into memory. - Reuse
CellStyleobjects; the number of distinct styles per workbook is limited and each new one adds overhead. - Write to a temporary file and rename it on success if you are overwriting an important workbook, so a crash does not leave a half-written file.
- Keep POI and its transitive dependencies at matching versions; mixing POI 4.x and 5.x JARs causes subtle runtime errors.
Troubleshooting
NoClassDefFoundErrororClassNotFoundExceptionfor POI classes: the dependency is missing or not on the runtime classpath. Runmvn dependency:treeorgradle dependenciesto confirm POI is resolved, and rebuild.InvalidFormatExceptionor "Your file cannot be opened": the file is not a real Excel file, is password-protected, or is an old format POI cannot parse. Test it by opening in Excel first.- File locked or "cannot access" on Windows: a previous run did not close the workbook. Close all streams, and if needed restart the JVM. Do not delete the file while it is open.
- Output file opens with a repair prompt: the stream was not flushed or the workbook was not closed. Wrap writes in try-with-resources and call
wb.write(fos)before the block ends. - Numbers appear as text or dates as serial numbers: the cell style is missing or wrong. Apply a
CellStylewith the correct data format, and for dates remember Excel stores them as numbers. - OutOfMemoryError on large files: switch to the streaming API (
SXSSFWorkbook/XSSFReader) or raise the heap with-Xmxas a temporary measure.
Frequently Asked Questions
Do I need Microsoft Excel installed to use Apache POI?
No. POI reads and writes the file format directly; Excel is only needed if you want to open the result to check it.
Which POI version should I use?
Use the latest stable 5.x release listed on Maven Central. Keep poi and poi-ooxml on the same version.
Can POI evaluate formulas?
Yes, with FormulaEvaluator from the workbook (wb.getCreationHelper().createFormulaEvaluator()). It handles common functions but not every Excel feature, so results can differ from Excel for complex formulas.
How do I read a password-protected workbook?
Use WorkbookFactory.create(inputStream, password) with the correct password. POI cannot open encrypted files without it.
Does POI work with .xls files?
Yes, via HSSFWorkbook or WorkbookFactory. The legacy .xls format has row and column limits, so prefer .xlsx for new files.
Why is my written file empty or zero bytes?
The output stream was not flushed or closed, or wb.write(fos) was never reached because of an exception. Use try-with-resources and check for swallowed exceptions.