Course – LS – All

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

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll show how to add a column to a sheet in an Excel file with Apache POI.

2. Apache POI

To begin with, we first need to add the poi-ooxml dependency to our project’s pom.xml file:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.5</version>
</dependency>

Apache POI uses the Workbook interface to represent an Excel file. It also uses SheetRow, and Cell interfaces to model different elements in an Excel file.

3. Add a New Column

In Excel, we sometimes want to add a new column over existing rows. To achieve this, we can go through each row and create a new cell at the end of the row:

void addColumn(Sheet sheet, CellType cellType) {
    for (Row currentRow : sheet) {
        currentRow.createCell(currentRow.getLastCellNum(), cellType);
    }
}

In this method, we use a loop to go through all rows of the input Excel sheet. For each row, we first find its last cell number and then create a new cell after the last cell.

4. Summary

In this quick article, we showed how to add a new column with Apache POI.  As always, the source code for the article is available over on GitHub.

Course – LS – All

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

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.