Adding a Column to an Excel Sheet Using Apache POI
Last updated: June 2, 2023
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.0.0</version>
</dependency>
Apache POI uses the Workbook interface to represent an Excel file. It also uses Sheet, Row, 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.