1. Introduction

Apache POI is an open-source library for software developers to create and manipulate Microsoft Office documents. Among other features, it allows developers to change document formatting programmatically.

In this article, we’ll discuss how to change cells’ style in Microsoft Excel when using a class called CellStyle. That is to say, using this class, we can write code to modify the style of cells in a Microsoft Excel document. Firstly, it is a feature provided by the Apache POI library that allows a style with multiple formatting properties to be created inside a workbook. Secondly, the style can then be applied to multiple cells in that workbook.

Besides that, we’ll also look at common pitfalls of using the CellStyle class.

2. Apache POI and Maven Dependency

Let’s add Apache POI as a dependency to our project pom.xml file:

<dependency>
    <groupId>org.apache.poi</groupId> 
    <artifactId>poi</artifactId> 
    <version>5.2.0</version> 
</dependency>

3. Creating CellStyle

Let’s start with instantiating CellStyle:

Workbook workbook = new XSSFWorkbook(fileLocation);
CellStyle cellStyle = wb.createCellStyle();

Next, well set the needed formatting property. For instance, the code below will set it to have a date format:

cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("m/d/yy h:mm"));

Now, let’s create an Apache POI workbook and get the first worksheet:

CellStyler styler = new CellStyler();
CellStyle style = styler.createWarningColor(workbook);

Cell cell1 = row1.createCell(0);
cell1.setCellStyle(style);
cell1.setCellValue("Hello");

Cell cell2 = row1.createCell(1);
cell2.setCellStyle(style);
cell2.setCellValue("world!");

Now, let’s save this workbook to a file and open the file in Microsoft Excel to view the font styling effect, where we should see:

Result of applying font style