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:
poifor the older .xls format andpoi-ooxmlfor .xlsx. If you only handle .xlsx,poi-ooxmlis 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
Add the dependency. In your
pom.xml, add adependencyblock insidedependencieswith groupIdorg.apache.poi, artifactIdpoi-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 thepoiartifact as well. In Gradle the equivalent line isimplementation 'org.apache.poi:poi-ooxml:5.2.5'in the dependencies block. Run a build so the JARs download before you write any code.Create a workbook-reading method. Import
org.apache.poi.ss.usermodel.WorkbookandWorkbookFactory. The cleanest pattern is a try-with-resources block:try (Workbook workbook = WorkbookFactory.create(new File("input.xlsx"))).WorkbookFactoryinspects the file and returns eitherXSSFWorkbookfor .xlsx orHSSFWorkbookfor .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.Get the sheet you want. Call
workbook.getSheetAt(0)for the first sheet, orworkbook.getSheet("Sheet1")by name. Sheet names are case-sensitive and can include spaces. If you do not know the name,workbook.getNumberOfSheets()andworkbook.getSheetName(i)let you list them.Iterate rows and cells. Loop with
for (Row row : sheet)to walk existing rows, or usesheet.getLastRowNum()and an index loop. Inside, loop over the cells withfor (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, aRowcan be null when a row was never created, so guard with a null check before reading.Read each cell according to its type. Call
cell.getCellType()and switch on it. ForSTRINGusegetStringCellValue(). ForNUMERICusegetNumericCellValue(), which returns a double, and checkDateUtil.isCellDateFormatted(cell)first if the column might hold dates, then convert withcell.getLocalDateTimeCellValue(). ForBOOLEANusegetBooleanCellValue(). ForFORMULA, callgetCachedFormulaResultType()to see what the formula produced, then read via the matching getter. ForBLANK, skip the cell. Throw or default on anything unexpected rather than assuming a string.Write a new workbook. Create an
XSSFWorkbook:try (Workbook workbook = new XSSFWorkbook()). Create a sheet withworkbook.createSheet("Data"), thenRow row = sheet.createRow(0)for the header androw.createCell(0).setCellValue("Name")and so on. Note thatcreateRowandcreateCellthrow anIllegalArgumentExceptionif that row or cell already exists, so usegetRowandgetCellfirst when you are updating rather than building.Save to a file. Open an
OutputStreamwithFiles.newOutputStream(Paths.get("output.xlsx"))and callworkbook.write(out). For .xls output, instantiateHSSFWorkbookinstead. Do not wrap the stream inFileOutputStreamand 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.Style what you write. For a bold header, call
workbook.createCellStyle(), thenFont font = workbook.createFont(),font.setBold(true),style.setFont(font), andcell.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 usesheet.setColumnWidth(index, width), remembering the width is in units of 1/256 of a character.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.