eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

In this tutorial, we’ll demonstrate the use of the Apache POI, JExcel, and Fastexcel APIs for working with Excel spreadsheets.

These libraries can be used to dynamically read, write and modify the content of an Excel spreadsheet and provide an effective way of integrating Microsoft Excel into a Java Application.

Further reading:

Insert a Row in Excel Using Apache POI

Learn how to inser a new row between two rows in an Excel file using the Apache POI library

Adding a Column to an Excel Sheet Using Apache POI

Learn how to add a column to an Excel sheet using Java with the Apache POI library.

Reading Values From Excel in Java

Learn how to access different cell values using Apache POI.

2. Maven Dependencies

To begin, we will need to add the following dependencies to our pom.xml file:

<dependency> 
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId> 
  <version>5.5.0</version> 
</dependency> 
<dependency> 
  <groupId>org.apache.poi</groupId> 
  <artifactId>poi-ooxml</artifactId> 
  <version>5.5.0</version> 
</dependency>
<dependency>
  <groupId>org.jxls</groupId>
  <artifactId>jxls-jexcel</artifactId>
  <version>1.0.9</version>
</dependency>
<dependency>
    <groupId>org.dhatim</groupId>
    <artifactId>fastexcel-reader</artifactId>
    <version>0.19.0</version>
</dependency>
<dependency>
    <groupId>org.dhatim</groupId>
    <artifactId>fastexcel</artifactId>
    <version>0.19.0</version>
</dependency>

The latest versions of poi, poi-ooxmljxls-jexcel, fastexcel-reader, and fastexcel can be downloaded from Maven Central.

3. Apache POI

The Apache POI library supports both .xls and .xlsx files and is a more complex library than other Java libraries for working with Excel files.

It provides the Workbook interface for modeling an Excel file, and the Sheet, Row, and Cell interfaces that model the elements of an Excel file, as well as implementations of each interface for both file formats.

When working with the newer .xlsx file format, we’d use the XSSFWorkbook, XSSFSheet, XSSFRow, and XSSFCell classes.

To work with the older .xls format, we use the HSSFWorkbook, HSSFSheet, HSSFRow, and HSSFCell classes.

3.1. Reading From Excel

Let’s create a method that opens a .xlsx file and then reads content from the first sheet of the file.

The method for reading cell content varies depending on the type of data in the cell. The type of cell content can be determined using the getCellType() method of the Cell interface.

First, let’s open the file from a given location:

FileInputStream file = new FileInputStream(new File(fileLocation));
Workbook workbook = new XSSFWorkbook(file);

Next, let’s retrieve the first sheet of the file and iterate through each row:

Sheet sheet = workbook.getSheetAt(0);

Map<Integer, List<String>> data = new HashMap<>();
int i = 0;
for (Row row : sheet) {
    data.put(i, new ArrayList<String>());
    for (Cell cell : row) {
        switch (cell.getCellType()) {
            case STRING: ... break;
            case NUMERIC: ... break;
            case BOOLEAN: ... break;
            case FORMULA: ... break;
            default: data.get(new Integer(i)).add(" ");
        }
    }
    i++;
}

Apache POI has different methods for reading each type of data. Let’s expand on the content of each switch case above.

When the cell type enum value is STRING, the content will be read using the getRichStringCellValue() method of the Cell interface:

data.get(new Integer(i)).add(cell.getRichStringCellValue().getString());

Cells having the NUMERIC content type can contain either a date or a number and are read in the following manner:

if (DateUtil.isCellDateFormatted(cell)) {
    data.get(i).add(cell.getDateCellValue() + "");
} else {
    data.get(i).add(cell.getNumericCellValue() + "");
}

For BOOLEAN values, we have the getBooleanCellValue() method:

data.get(i).add(cell.getBooleanCellValue() + "");

And when the cell type is FORMULA, we can use the getCellFormula() method:

data.get(i).add(cell.getCellFormula() + "");

3.2. Writing to Excel

Apache POI uses the same interfaces presented in the previous section for writing to an Excel file and has better support for styling than JExcel.

Let’s create a method that writes a list of persons to a sheet titled “Persons”.

First, we will create and style a header row that contains “Name” and “Age” cells:

Workbook workbook = new XSSFWorkbook();

Sheet sheet = workbook.createSheet("Persons");
sheet.setColumnWidth(0, 6000);
sheet.setColumnWidth(1, 4000);

Row header = sheet.createRow(0);

CellStyle headerStyle = workbook.createCellStyle();
headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

XSSFFont font = ((XSSFWorkbook) workbook).createFont();
font.setFontName("Arial");
font.setFontHeightInPoints((short) 16);
font.setBold(true);
headerStyle.setFont(font);

Cell headerCell = header.createCell(0);
headerCell.setCellValue("Name");
headerCell.setCellStyle(headerStyle);

headerCell = header.createCell(1);
headerCell.setCellValue("Age");
headerCell.setCellStyle(headerStyle);

Next, let’s write the content of the table in a different style:

CellStyle style = workbook.createCellStyle();
style.setWrapText(true);

Row row = sheet.createRow(2);
Cell cell = row.createCell(0);
cell.setCellValue("John Smith");
cell.setCellStyle(style);

cell = row.createCell(1);
cell.setCellValue(20);
cell.setCellStyle(style);

Finally, let’s write the content to a “temp.xlsx” file in the current directory and close the workbook:

File currDir = new File(".");
String path = currDir.getAbsolutePath();
String fileLocation = path.substring(0, path.length() - 1) + "temp.xlsx";

FileOutputStream outputStream = new FileOutputStream(fileLocation);
workbook.write(outputStream);
workbook.close();

Let’s test the above methods in a JUnit test that writes content to the temp.xlsx file and then reads the same file to verify it contains the text we have written:

public class ExcelIntegrationTest {

    private ExcelPOIHelper excelPOIHelper;
    private static String FILE_NAME = "temp.xlsx";
    private String fileLocation;

    @Before
    public void generateExcelFile() throws IOException {
        File currDir = new File(".");
        String path = currDir.getAbsolutePath();
        fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;

        excelPOIHelper = new ExcelPOIHelper();
        excelPOIHelper.writeExcel();
    }

    @Test
    public void whenParsingPOIExcelFile_thenCorrect() throws IOException {
        Map<Integer, List<String>> data
          = excelPOIHelper.readExcel(fileLocation);

        assertEquals("Name", data.get(0).get(0));
        assertEquals("Age", data.get(0).get(1));

        assertEquals("John Smith", data.get(1).get(0));
        assertEquals("20", data.get(1).get(1));
    }
}

4. JExcel

The JExcel library is a lightweight library with the advantage that it’s easier to use than Apache POI, but with the disadvantage that it only provides support for processing Excel files in the .xls (1997-2003) format.

At the moment, .xlsx files are not supported.

4.1. Reading From Excel

In order to work with Excel files, this library provides a series of classes that represent the different parts of an Excel file. The Workbook class represents the entire collection of sheets. The Sheet class represents a single sheet, and the Cell class represents a single cell of a spreadsheet.

Let’s write a method that creates a workbook from a specified Excel file, gets the first sheet of the file, and then traverses its content and adds each row in a HashMap:

public class JExcelHelper {

    public Map<Integer, List<String>> readJExcel(String fileLocation) 
      throws IOException, BiffException {
 
        Map<Integer, List<String>> data = new HashMap<>();

        Workbook workbook = Workbook.getWorkbook(new File(fileLocation));
        Sheet sheet = workbook.getSheet(0);
        int rows = sheet.getRows();
        int columns = sheet.getColumns();

        for (int i = 0; i < rows; i++) {
            data.put(i, new ArrayList<String>());
            for (int j = 0; j < columns; j++) {
                data.get(i)
                  .add(sheet.getCell(j, i)
                  .getContents());
            }
        }
        return data;
    }
}

4.2. Writing to Excel

For writing to an Excel file, the JExcel library offers classes similar to the ones used above, which model a spreadsheet file: WritableWorkbook, WritableSheet, and WritableCell.

The WritableCell class has subclasses corresponding to the different types of content that can be written: Label, DateTime, Number, Boolean, Blank, and Formula.

This library also supports basic formatting, such as controlling font, color, and cell width.

Let’s write a method that creates a workbook called “temp.xls” in the current directory and then writes the same content we wrote in the Apache POI section.

First, let’s create the workbook:

File currDir = new File(".");
String path = currDir.getAbsolutePath();
String fileLocation = path.substring(0, path.length() - 1) + "temp.xls";

WritableWorkbook workbook = Workbook.createWorkbook(new File(fileLocation));

Next, let’s create the first sheet and write the header of the Excel file, containing the “Name” and “Age” cells:

WritableSheet sheet = workbook.createSheet("Sheet 1", 0);

WritableCellFormat headerFormat = new WritableCellFormat();
WritableFont font
  = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD);
headerFormat.setFont(font);
headerFormat.setBackground(Colour.LIGHT_BLUE);
headerFormat.setWrap(true);

Label headerLabel = new Label(0, 0, "Name", headerFormat);
sheet.setColumnView(0, 60);
sheet.addCell(headerLabel);

headerLabel = new Label(1, 0, "Age", headerFormat);
sheet.setColumnView(0, 40);
sheet.addCell(headerLabel);

With a new style, let’s write the content of the table we’ve created:

WritableCellFormat cellFormat = new WritableCellFormat();
cellFormat.setWrap(true);

Label cellLabel = new Label(0, 2, "John Smith", cellFormat);
sheet.addCell(cellLabel);
Number cellNumber = new Number(1, 2, 20, cellFormat);
sheet.addCell(cellNumber);

It’s very important to remember to write to the file and close it at the end so it can be used by other processes, using the write() and close() methods of the Workbook class:

workbook.write();
workbook.close();

5. Fastexcel

Fastexcel is an easy-to-use library with limited features and a lower memory footprint compared to Apache POI.

Its multi-threaded support using CompletableFuture makes it a great alternative when working with large files that aren’t feature-extensive. At the moment, the library has only basic style support and doesn’t support graphs.

5.1. Reading From Excel

Let’s write a method to access the Excel file and read the data from its first sheet. Let’s add the data to a Map of row indices as keys and a list of the content from that row as value:

public class FastexcelHelper {

    public Map<Integer, List<String>> readExcel(String fileLocation) throws IOException {
        Map<Integer, List<String>> data = new HashMap<>();

        try (FileInputStream file = new FileInputStream(fileLocation); ReadableWorkbook wb = new ReadableWorkbook(file)) {
            Sheet sheet = wb.getFirstSheet();
            try (Stream<Row> rows = sheet.openStream()) {
                rows.forEach(r -> {
                    data.put(r.getRowNum(), new ArrayList<>());

                    for (Cell cell : r) {
                        data.get(r.getRowNum()).add(cell.getRawValue());
                    }
                });
            }
        }

        return data;
    }
}

Here, we’re using cell.getRawValue() which returns the value of that cell as a String. Alternatively, based on CellType we can use the getCellAsBoolean(int cellIndex), getCellAsDate(int cellIndex), getCellAsString(int cellIndex) or getCellAsNumber(int cellIndex) methods from the Row class to read a cell’s content.

5.2. Writing to Excel

Unlike the libraries mentioned above, Fastexcel uses different interfaces to write to an Excel file than the ones used to read Excel.

We’ll begin by creating a Workbook from an OutputStream. We’ll then write the “Name” and “Age” headers in the default first sheet and add style details to the cells. Next, let’s add another row with a person’s name and age:

public void writeExcel() throws IOException {
    File currDir = new File(".");
    String path = currDir.getAbsolutePath();
    String fileLocation = path.substring(0, path.length() - 1) + "fastexcel.xlsx";

    try (OutputStream os = Files.newOutputStream(Paths.get(fileLocation)); Workbook wb = new Workbook(os, "MyApplication", "1.0")) {
        Worksheet ws = wb.newWorksheet("Sheet 1");
        ws.width(0, 25);
        ws.width(1, 15);
        
        ws.range(0, 0, 0, 1).style().fontName("Arial").fontSize(16).bold().fillColor("3366FF").set();
        ws.value(0, 0, "Name");
        ws.value(0, 1, "Age");
        
        ws.range(2, 0, 2, 1).style().wrapText(true).set();
        ws.value(2, 0, "John Smith");
        ws.value(2, 1, 20L);
    }
}

Let’s write a small test to verify our code:

@Test
public void whenParsingExcelFile_thenCorrect() throws IOException {
    Map<Integer, List<String>> data = fastexcelHelper.readExcel(fileLocation);

    assertEquals("Name", data.get(1).get(0));
    assertEquals("Age", data.get(1).get(1));

    assertEquals("John Smith", data.get(3).get(0));
    assertEquals("20", data.get(3).get(1));
}

Here, we also see that the Row class in the fastexcel-reader library uses the variable rowNum with an offset of 1. Whereas, the value(int r, int c, Object value) method from the Worksheet class from the fastexcel library expects the row’s index with an offset of 0.

6. Conclusion

In this article, we saw how to use the Apache POI API, JExcel API, and Fastexcel API to read and write an Excel file from a Java program.

When deciding on which library to use, we should consider the benefits and drawbacks of each library. For example, Apache POI is feature-rich and has support for graphs but has a high memory footprint. In contrast, Fastexcel has limited features but consumes less memory than Apache POI.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)