You can read and write Excel files in Java with a small amount of code using Apache POI, the long-standing open-source library that handles both the older .xls format and the newer .xlsx format. You add the POI dependency to your project, open a workbook object, loop through sheets, rows and cells to read data, and build the same structure in reverse to write a file. The whole job is a few dozen lines once the dependency is in place. Everything below uses Maven with Apache POI 5.x, which is the version most projects run today, though the API you use here has been stable for years.

What You'll Need

  • A Java project built with Maven or Gradle (a plain project with manually added JARs also works, but is fiddlier)
  • Apache POI dependencies: poi for the older .xls format and poi-ooxml for .xlsx. If you only handle .xlsx, poi-ooxml is enough because it pulls the base library in transitively.
  • A JDK, version 8 or newer
  • A spreadsheet to test against, either one you already have or one your code creates
  • Write permission to whatever folder you save output into

Step-by-Step

  1. Add the dependency. In your pom.xml, add a dependency block inside dependencies with groupId org.apache.poi, artifactId poi-ooxml, and a current 5.x version. Avoid pinning a very old 3.x or 4.x release, because the cell type handling changed and most tutorials you find online predate the change. If you also need to read legacy .xls files, add the poi artifact as well. In Gradle the equivalent line is implementation 'org.apache.poi:poi-ooxml:5.2.5' in the dependencies block. Run a build so the JARs download before you write any code.

  2. Create a workbook-reading method. Import org.apache.poi.ss.usermodel.Workbook and WorkbookFactory. The cleanest pattern is a try-with-resources block: try (Workbook workbook = WorkbookFactory.create(new File("input.xlsx"))). WorkbookFactory inspects the file and returns either XSSFWorkbook for .xlsx or HSSFWorkbook for .xls, so you do not need to branch on file type yourself. The try-with-resources matters because workbooks hold file handles and, for large files, memory.

  3. Get the sheet you want. Call workbook.getSheetAt(0) for the first sheet, or workbook.getSheet("Sheet1") by name. Sheet names are case-sensitive and can include spaces. If you do not know the name, workbook.getNumberOfSheets() and workbook.getSheetName(i) let you list them.

  4. Iterate rows and cells. Loop with for (Row row : sheet) to walk existing rows, or use sheet.getLastRowNum() and an index loop. Inside, loop over the cells with for (Cell cell : row). Two caveats: getLastRowNum() returns a zero-based index of the last row, and it counts rows that contain only formatting, so an empty-looking sheet can report rows you do not want. Also, a Row can be null when a row was never created, so guard with a null check before reading.

  5. Read each cell according to its type. Call cell.getCellType() and switch on it. For STRING use getStringCellValue(). For NUMERIC use getNumericCellValue(), which returns a double, and check DateUtil.isCellDateFormatted(cell) first if the column might hold dates, then convert with cell.getLocalDateTimeCellValue(). For BOOLEAN use getBooleanCellValue(). For FORMULA, call getCachedFormulaResultType() to see what the formula produced, then read via the matching getter. For BLANK, skip the cell. Throw or default on anything unexpected rather than assuming a string.

  6. Write a new workbook. Create an XSSFWorkbook: try (Workbook workbook = new XSSFWorkbook()). Create a sheet with workbook.createSheet("Data"), then Row row = sheet.createRow(0) for the header and row.createCell(0).setCellValue("Name") and so on. Note that createRow and createCell throw an IllegalArgumentException if that row or cell already exists, so use getRow and getCell first when you are updating rather than building.

  7. Save to a file. Open an OutputStream with Files.newOutputStream(Paths.get("output.xlsx")) and call workbook.write(out). For .xls output, instantiate HSSFWorkbook instead. Do not wrap the stream in FileOutputStream and also use try-with-resources for the workbook without closing the stream; the write will flush but the stream still needs closing. A try-with-resources covering both is the safe pattern.

  8. Style what you write. For a bold header, call workbook.createCellStyle(), then Font font = workbook.createFont(), font.setBold(true), style.setFont(font), and cell.setCellStyle(style). Create styles once per workbook and reuse them; a new style per cell bloats the file and eventually errors out on the style limit. For column widths use sheet.setColumnWidth(index, width), remembering the width is in units of 1/256 of a character.

  9. Run and verify the round trip. Write a file, then read it back with the reading method and print the values. This catches the most common problems early: numbers arriving as strings, dates arriving as raw serial numbers, and empty cells throwing null pointer exceptions.

Common Mistakes

The first is mixing the APIs: using XSSFWorkbook directly for a file that might be .xls, which throws OfficeXmlFileException. Let WorkbookFactory decide the format on the read side. The second is reading every cell as a string after calling getStringCellValue() without checking the type, which throws IllegalStateException on numeric cells. The third is treating getLastRowNum() as a count; it is an index, so the number of rows is one more than that value, and it still includes formatted-but-empty rows. The fourth is leaving workbooks unclosed, which on Windows keeps a lock on the file so the next write fails with a file-in-use error. The fifth is using the wrong dependency, such as only poi for an .xlsx file, which throws NoClassDefFoundError for OOXML classes at runtime even though the code compiles.

Tips

Prefer the SXSSFWorkbook class for generating files with tens of thousands of rows; it streams rows to disk and avoids the memory pressure of holding the whole workbook in heap. Keep the JVM heap in mind: large XSSFWorkbook reads can need far more memory than the file size suggests. Never hardcode sheet or file names that could vary between inputs; read them from configuration. If you are writing dates, create a cell style with a date format such as workbook.createDataFormat().getFormat("yyyy-mm-dd"), otherwise the cell shows a raw number. Log which row and cell failed when parsing, because a malformed spreadsheet that throws halfway through is hard to diagnose otherwise. Finally, validate file extensions and reject or rename temporary Office files (those starting with ~$) that users sometimes upload by accident.

Troubleshooting

NoClassDefFoundError or ClassNotFoundException for XSSFWorkbook means the OOXML dependency is missing; add poi-ooxml rather than only poi. A NullPointerException while iterating usually means a row or cell was never created; add null checks or use sheet.getRow(i) with a guard. IllegalStateException: Cannot get a STRING value from a NUMERIC cell means you skipped the type check; switch on getCellType(). OfficeXmlFileException means the file is .xlsx but you opened it as HSSFWorkbook, or vice versa. If workbook.write fails with a file-in-use error, close any other workbook, stream or viewer holding the path. If dates come back wrong by a day, check that the spreadsheet was created in Excel with the correct date system; the library follows the workbook's stored base date, and confusion between the two date systems is the usual cause. If the output file builds but Excel reports corruption, confirm you closed the workbook and the stream in the right order and that you did not reuse a style object created by a different workbook.

Frequently Asked Questions

Do I need a paid library to work with Excel in Java?

No. Apache POI is open source and covers .xls and .xlsx for both reading and writing. Commercial libraries exist but are optional.

Which class should I use, XSSFWorkbook or SXSSFWorkbook?

Use XSSFWorkbook for normal reads and small writes. Use SXSSFWorkbook when you are creating very large files and want to keep memory use down.

Can POI evaluate formulas instead of reading cached values?

Yes, via FormulaEvaluator from workbook.getCreationHelper().createFormulaEvaluator(). Without it you read the cached result that Excel last stored, which may be missing if the file was generated by another program.

Why does my number arrive as a date or a date as a number?

Excel stores dates as serial numbers. Check DateUtil.isCellDateFormatted(cell) before converting, and always treat plain numeric cells as doubles.

Does POI preserve formatting and charts when I read and rewrite a file?

Reading is safe. Rewriting works on what POI models, but complex charts, pivot tables and some drawings may not survive a full round trip; test with your real files before relying on it.

Can I use this on Android?

POI is a full JVM library and is not officially supported on Android; expect problems with dependencies and memory. Parse spreadsheets server-side instead.