Apache POI tutorial: read, write and style Excel files in Java

Create, style and read Excel .xlsx files in Java with Apache POI 5: headers, dates, number formats, formulas, frozen panes, reading cells safely and streaming large sheets with SXSSF.

Written for Apache POI 5.3 and JDK 21

In this JavaAnt guide, we cover creating and writing Excel files in Java. Apache POI is the standard Java library for Microsoft Office formats, and its spreadsheet API is what most Java code uses to export reports to Excel or import a spreadsheet someone uploaded. This tutorial writes a styled .xlsx file with dates, money and a total formula, reads it back safely, and then handles files too large to keep in memory.

Add the dependency

For .xlsx files you need poi-ooxml, which pulls in the core poi module:

pom.xml
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.3.0</version>
</dependency>

With Gradle: implementation("org.apache.poi:poi-ooxml:5.3.0"). POI logs through Log4j 2's API, so if you see a warning that no Log4j implementation was found, add a Log4j binding or the log4j-to-slf4j bridge your project already uses.

The object model in one minute

A Workbook contains Sheets, a sheet contains Rows, a row contains Cells. Rows and cells are created on demand, so a new sheet has none. The interfaces in org.apache.poi.ss.usermodel have three implementations:

ClassFormatUse it for
XSSFWorkbook.xlsx (Excel 2007 and newer)Reading and writing normal files
SXSSFWorkbook.xlsx, streamingWriting large files with little memory
HSSFWorkbook.xls (Excel 97-2003)Old files only

Code written against the interfaces (Workbook, Sheet, Row, Cell) works with all three, so you can switch later without rewriting.

Write a styled workbook

The example exports orders: a bold header row, a date column, a money column and a total.

OrdersExport.java
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDate;
import java.util.List;

public final class OrdersExport {
    public record Order(String number, String customer, LocalDate date, BigDecimal amount) {}

    public static void write(List<Order> orders, Path target) throws IOException {
        try (Workbook wb = new XSSFWorkbook(); OutputStream out = Files.newOutputStream(target)) {
            Sheet sheet = wb.createSheet("Orders");
            DataFormat format = wb.createDataFormat();

            Font bold = wb.createFont();
            bold.setBold(true);
            CellStyle header = wb.createCellStyle();
            header.setFont(bold);
            header.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            header.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            header.setBorderBottom(BorderStyle.THIN);

            CellStyle dateStyle = wb.createCellStyle();
            dateStyle.setDataFormat(format.getFormat("yyyy-mm-dd"));
            CellStyle money = wb.createCellStyle();
            money.setDataFormat(format.getFormat("#,##0.00"));

            String[] titles = {"Order", "Customer", "Date", "Amount"};
            Row head = sheet.createRow(0);
            for (int i = 0; i < titles.length; i++) {
                Cell cell = head.createCell(i);
                cell.setCellValue(titles[i]);
                cell.setCellStyle(header);
            }

            int r = 1;
            for (Order order : orders) {
                Row row = sheet.createRow(r++);
                row.createCell(0).setCellValue(order.number());
                row.createCell(1).setCellValue(order.customer());
                Cell date = row.createCell(2);
                date.setCellValue(order.date());
                date.setCellStyle(dateStyle);
                Cell amount = row.createCell(3);
                amount.setCellValue(order.amount().doubleValue());
                amount.setCellStyle(money);
            }

            Row total = sheet.createRow(r);
            total.createCell(2).setCellValue("Total");
            Cell sum = total.createCell(3);
            sum.setCellFormula("SUM(D2:D" + r + ")");
            sum.setCellStyle(money);

            sheet.createFreezePane(0, 1);
            sheet.setAutoFilter(new CellRangeAddress(0, r - 1, 0, titles.length - 1));
            for (int i = 0; i < titles.length; i++) {
                sheet.autoSizeColumn(i);
            }
            wb.write(out);
        }
    }
}

A few things in there are easy to get wrong.

Styles belong to the workbook, not the cell. Create each CellStyle once and reuse it. Creating a new style per cell works for a hundred rows and then fails, because a workbook can hold at most about 64,000 styles.

Excel stores dates as numbers. setCellValue(LocalDate) writes the number, but without a date format the cell shows something like 46351. The dateStyle above is what makes it display as a date. The same applies to money: the value is a number, the #,##0.00 format only changes how it looks, so the spreadsheet can still sum it.

Formulas are written without the leading =. Rows in the API are zero-based but rows in formulas are one-based, which is why the data starting at row index 1 is D2 in the formula. POI writes the formula; Excel calculates it when the file opens.

autoSizeColumn measures text with Java's font rendering, so it needs fonts installed. On a minimal Linux server or container you may see errors about fonts or Toolkit; install a basic font package (for example fontconfig and a DejaVu font), or set fixed widths with sheet.setColumnWidth(i, 20 * 256), where the unit is 1/256 of a character.

Read a workbook safely

Reading is where real-world files bite: empty cells, numbers stored as text, dates that are just numbers, and formulas. DataFormatter turns any cell into the string Excel would display, which is the safest way to read text-like columns:

OrdersImport.java
import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public final class OrdersImport {
    public static List<OrdersExport.Order> read(File file) throws IOException {
        DataFormatter text = new DataFormatter();
        List<OrdersExport.Order> orders = new ArrayList<>();
        try (Workbook wb = WorkbookFactory.create(file, null, true)) {
            Sheet sheet = wb.getSheetAt(0);
            for (Row row : sheet) {
                if (row.getRowNum() == 0) continue;
                Cell dateCell = row.getCell(2, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
                Cell amountCell = row.getCell(3, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
                if (dateCell == null || amountCell == null
                        || dateCell.getCellType() != CellType.NUMERIC
                        || amountCell.getCellType() != CellType.NUMERIC) {
                    continue; // skips the total row and any incomplete rows
                }
                orders.add(new OrdersExport.Order(
                        text.formatCellValue(row.getCell(0)).strip(),
                        text.formatCellValue(row.getCell(1)).strip(),
                        dateCell.getLocalDateTimeCellValue().toLocalDate(),
                        BigDecimal.valueOf(amountCell.getNumericCellValue())));
            }
        }
        return orders;
    }
}

WorkbookFactory.create(file, null, true) opens the file read-only (the null is the password) and detects .xls versus .xlsx for you. The for (Row row : sheet) loop skips rows that do not exist in the file, so do not rely on getRowNum() being consecutive. getCell with RETURN_BLANK_AS_NULL gives you null for both missing and blank cells, so one check covers both.

To read a formula's result rather than the formula text, pass a FormulaEvaluator to the formatter: text.formatCellValue(cell, wb.getCreationHelper().createFormulaEvaluator()). For a cell you already know is numeric, getNumericCellValue() returns the cached result Excel saved, which is enough for files saved by Excel itself.

Checking getCellType() before calling a typed getter matters: getNumericCellValue() on a text cell throws IllegalStateException: Cannot get a NUMERIC value from a STRING cell. Spreadsheets edited by people often contain numbers typed as text, so decide per column whether to parse text or reject the row.

Write large files with SXSSF

XSSFWorkbook keeps the whole workbook in memory, and a few hundred thousand rows can use gigabytes of heap. SXSSFWorkbook keeps a window of rows in memory and flushes older rows to a temporary file:

Java
try (SXSSFWorkbook wb = new SXSSFWorkbook(100); OutputStream out = Files.newOutputStream(target)) {
    SXSSFSheet sheet = wb.createSheet("Orders");
    sheet.trackAllColumnsForAutoSizing();
    // create rows exactly as before, in order
    wb.write(out);
} // close() also deletes the temporary files

The trade-off is that rows outside the window are gone from memory: you can only write top to bottom and cannot go back to edit earlier rows. autoSizeColumn only measures the rows it has tracked, which is why the column tracking call is there. In POI 5, close() deletes the temporary files, which is why dispose() is now deprecated; on POI 4 and older, call wb.dispose() after writing or the temporary files stay on disk.

For reading very large files, POI has an event-based API (the XSSF SAX reader) that never builds the object model; it is more code, so reach for it only when WorkbookFactory runs out of memory.

What changed from POI 3

Tutorials written for POI 3.x compare cell types with integer constants such as Cell.CELL_TYPE_NUMERIC and refer to colours as HSSFColor.GREY_25_PERCENT.index. Both were removed: POI 4 and newer use the CellType enum and IndexedColors. POI 4 also dropped Java 6 and 7, and POI 5 needs Java 8 or newer and moved logging to Log4j 2. If you are upgrading old code, compile against POI 5 and fix the errors one by one; the object model itself (Workbook, Sheet, Row, Cell) is the same.

The order rows above are a natural fit for Java records, which is why Order is one. The Apache POI spreadsheet guide has short examples for merged cells, images, comments and data validation.

About Glenna Babshire29 Articles
Java & libraries writer. Writes the Java tutorials: the language from Java 21 on, encryption, configuration and the libraries around it.