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

1. Overview

In this tutorial, we’ll discuss how to find the last row in an Excel spreadsheet using Java and Apache POI.

Firstly, we’ll see how to fetch a single row from the file using Apache POI. Then, we’ll look at methods for counting all rows in a worksheet. Finally, we’ll combine them to fetch the last row of a given sheet.

2. Fetch a Single Row

As we already know, the Apache POI provides an abstract layer to represent Microsoft documents, including Excel, in Java. We can access the sheets in a file and even read and modify each cell.

Let’s start by fetching a single row from our Excel file. Before we move on, we need to get the Worksheet from the file:

Workbook workbook = new XSSFWorkbook(fileLocation);
Sheet sheet = workbook.getSheetAt(0);

The Workbook is a Java representation of the Excel file, while Sheet is the main structure within a Workbook. The Worksheet is the most common subtype of Sheet, representing a grid of cells.

When we open our worksheet in Java, we can access the data it contains, i.e., the row data. To fetch a single row, we can use the getRow(int) method:

Row row = sheet.getRow(2);

The method returns the Row object – the high-level representation of a single row from the Excel file, or null if the row doesn’t exist.

As we see, we need to supply a single parameter, the index (0-based) of the requested row. Unfortunately, there is no API available to get the last row directly.

3. Find the Count of Rows

We’ve just learned how to get a single row from an Excel file using Java. Now, let’s find the index of the last row on a given Sheet.

Apache POI provides two methods that help count rows: getLastRowNum() and getPhysicalNumberOfRows(). Let’s take a look at each of them.

3.1. Using getLastRowNum()

According to the documentation, the getLastRowNum() method returns the number (0-based) of the last initialized row on the worksheet, or -1 if no row exists:

int lastRowNum = sheet.getLastRowNum();

Once we fetched lastRowNum, we should now easily access the last row using the getRow() method.

We should note that rows that had content before and were set to empty later might still be counted as rows. Therefore, the result may not be as expected. To understand this, we need to learn more about physical rows.

3.2. Using getPhysicalNumberOfRows()

Inspecting the Apache POI documentation, we can find a special term related to the rows – the physical row.

A row is always interpreted as physical whenever it contains any data. The row is initialized not only if any cells in that row contain text or formulas but also if they have some data about formatting, e.g., the background color, the row height, or non-default font used. In other words, each row that is initialized is also physical.

To get the count of physical rows, Apache POI provides the getPhysicalNumberOfRows() method:

int physicalRows = sheet.getPhysicalNumberOfRows();

According to the physical row explanation, the result may differ from the number obtained with the getLastRowNum() method.

4. Fetch the Last Row

Now, let’s test both methods against a more complex Excel grid:

baeldung lastrow

Here, the leading rows contain the text data, the value calculated by the formula (=A1), and the background color changed accordingly. Then, the 4th row has modified height, while the 5th and 6th rows are untouched. The 7th row contains text again. On the 8th row, the text was previously formatted but later cleared. The 9th and subsequent rows weren’t edited.

Let’s check the results of the count methods:

assertEquals(7, sheet.getLastRowNum());
assertEquals(6, sheet.getPhysicalNumberOfRows());

As we mentioned before, the last row number and the physical number of rows are different in some cases.

Let’s now fetch rows based on their index:

assertNotNull(sheet.getRow(0)); // data
assertNotNull(sheet.getRow(1)); // formula
assertNotNull(sheet.getRow(2)); // green
assertNotNull(sheet.getRow(3)); // height
assertNull(sheet.getRow(4));
assertNull(sheet.getRow(5));
assertNotNull(sheet.getRow(6)); // last?
assertNotNull(sheet.getRow(7)); // cleared later
assertNull(sheet.getRow(8));
...

As we can see, the getPhysicalNumberOfRows() returns the total number of not-null (i.e., initialized) Rows in the worksheet. The getLastRowNum() value is the index of the last not-null Row.

Therefore, we can fetch the last row on the sheet:

Row lastRow = null;
int lastRowNum = sheet.getLastRowNum();
if (lastRowNum >= 0) {
    lastRow = sheet.getRow(lastRowNum);
}

However, we have to remember that the last row returned by Apache POI is not always the one where text or formula is shown, especially in some UI editors such as Microsoft Excel.

5. Conclusion

In this article, we inspected the Apache POI API and fetched the last row from a given Excel file.

We started by revisiting some of the basic methods to open a spreadsheet in Java. We then introduced the getRow(int) method to retrieve a single Row. After that, we checked the values of getLastRowNum() and getPhysicalNumberOfRows() and explained their difference. Finally, we checked all the methods against an Excel grid to fetch the last row.

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)