Font in excel file using Apache POI in Java

I am going to show you here how to work with font in excel file. With this example I will show you how to create different fonts for text and put it in an excel file using Apache POI in Java language.

The Apache POI is to create and maintain Java APIs for manipulating various file formats based upon the Office Open XML standards (OOXML) and Microsoft’s OLE 2 Compound Document format (OLE2).

Prerequisites

Java at least 8, maven 3.6.3, gradle 6.5.1, Apache POI 3.15 or 4.1.1 or 4.1.2

Project Setup

You need to create a maven or gradle project in your favorite IDE or tool. The name of the project is apache-poi-excel-different-fonts.

Here I will add apache poi API as a dependency for working with Microsoft word document or even you can work with open source word document.

If you are creating gradle based project then you can use below build.gradle script:

plugins {
    id 'java-library'
}

sourceCompatibility = 12
targetCompatibility = 12

repositories {
    jcenter()
}

dependencies {
    implementation 'org.apache.poi:poi-ooxml:4.1.2'
    
    //required only for jdk 9 or above
    implementation('com.fasterxml.jackson.core:jackson-databind:2.11.2')
}

If you are creating maven based project then you can use below pom.xml file:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.roytuts</groupId>
	<artifactId>apache-poi-excel-different-fonts</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>at least 1.8</java.version>
		<poi.version>3.15 or 4.1.1 or 4.1.2</poi.version>
	</properties>
	
	<dependencies>
		<!-- apache poi for xlsx, docx etc reading/writing -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>${poi.version}</version>
		</dependency>
		
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.11.2</version>
		</dependency>
	</dependencies>
	
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
                <configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Fonts Style in Excel

Now I am going to create fonts with different styles in excel file. The similar concept can be applied to apply more styles on different fonts.

You can create two different types of excel files having extensions xls or xlsx.

package com.roytuts.apache.poi.excel.different.fonts;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

public class StyleExcelFontsApp {

	public static void main(String[] args) {
		final String fileName = "excel-fonts.xlsx";
		styleFontsInExcel(fileName);
	}

	public static void styleFontsInExcel(final String fileName) {
		// get the file extension
		String fileExt = PoiUtils.getFileExtension(fileName);
		Workbook workbook = null;

		// based on file extension create Workbook object
		if (".xls".equalsIgnoreCase(fileExt)) {
			workbook = PoiUtils.getHSSFWorkbook();
		} else if (".xlsx".equalsIgnoreCase(fileExt)) {
			workbook = PoiUtils.getXSSFWorkbook();
		}

		// create Sheet object
		// sheet name must not exceed 31 characters
		// the name must not contain 0x0000, 0x0003, colon(:), backslash(\),
		// asterisk(*), question mark(?), forward slash(/), opening square
		// bracket([), closing square bracket(])
		Sheet sheet = workbook.createSheet("my_sheet");

		sheet.setColumnWidth(0, 9000);
		sheet.setColumnWidth(1, 9000);
		sheet.setColumnWidth(2, 9000);

		// Create first row. Rows are 0 based.
		Row row = sheet.createRow((short) 0);

		// Create a cell
		Font font1 = workbook.createFont();
		font1.setFontHeightInPoints((short) 16);
		font1.setFontName("Courier New");
		font1.setItalic(true);
		font1.setStrikeout(true);

		CellStyle cellStyle1 = workbook.createCellStyle();
		cellStyle1.setFont(font1);

		Cell cell = row.createCell(0);
		cell.setCellValue("This is a Courier New Font");
		cell.setCellStyle(cellStyle1);

		Font font2 = workbook.createFont();
		font2.setFontHeightInPoints((short) 18);
		font2.setFontName("Arial");
		font2.setItalic(true);
		font2.setStrikeout(true);

		CellStyle cellStyle2 = workbook.createCellStyle();
		cellStyle2.setFont(font2);

		cell = row.createCell(1);
		cell.setCellValue("This is an Arial Font");
		cell.setCellStyle(cellStyle2);

		Font font3 = workbook.createFont();
		font3.setFontHeightInPoints((short) 18);
		font3.setFontName("Garamond");
		font3.setItalic(true);
		// font3.setStrikeout(true);
		CellStyle cellStyle3 = workbook.createCellStyle();
		cellStyle3.setFont(font3);

		cell = row.createCell(2);
		cell.setCellValue("This is a Garamond Font");
		cell.setCellStyle(cellStyle3);

		FileOutputStream fileOut = null;
		try {
			fileOut = new FileOutputStream(fileName);
			workbook.write(fileOut);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fileOut.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

Testing the Application

Executing the above code the following output will be produced in the excel file. The excel file gets created under the project’s root directory.

different fonts in excel file using apache poi

Source Code

Download

That’s all. Thanks for reading.

Related posts

Leave a Comment