Text Alignment In Excel File Using Apache POI In Java

I this example I will show you how to align text in an excel file using Apache POI in Java language. The text can be aligned left, right, center, justify using apache poi library.

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).

You can read and write MS Excel files using Java. In addition, you can read and write MS Word and MS PowerPoint files using Java. Apache POI is the Java Excel files.

text alignment in excel file

Prerequisites

Java 8+, maven 3.6.3/3.8.2, gradle 6.5.1, Apache POI 3.15/4.1.1/4.1.2/5.0.0

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-text-alignment.

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-text-alignment</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>

You can use the following pom.xml file if you are using maven build tool for your project:

<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-text-alignment</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>8</maven.compiler.source>
		<maven.compiler.target>8</maven.compiler.target>
		<poi.version>5.0.0</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>
			</plugin>
		</plugins>
	</build>
</project>

Excel Text Alignment

In the following code I am going to put texts in separate cells with left, right, center and justify alignments.

The following code has the option to generate xls and xlsx file types.

package com.roytuts.apache.poi.excel.text.alignment;

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.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

public class ExcelTextAlignmentApp {

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

	public static void excelTextAlignment(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, 3000);
		sheet.setColumnWidth(1, 9000);
		sheet.setColumnWidth(2, 9000);
		sheet.setColumnWidth(3, 9000);

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

		// Create a cell
		// put a value in cell.
		CellStyle cellStyle1 = workbook.createCellStyle();
		cellStyle1.setWrapText(true);

		// justify text alignment
		cellStyle1.setAlignment(HorizontalAlignment.JUSTIFY);
		Cell cell = row.createCell(0);
		cell.setCellValue("This is Justify Alignment");
		cell.setCellStyle(cellStyle1);

		CellStyle cellStyle2 = workbook.createCellStyle();
		cellStyle2.setWrapText(true);

		// text left alignment
		cellStyle2.setAlignment(HorizontalAlignment.LEFT);
		cell = row.createCell(1);
		cell.setCellValue("This is Left Alignment");
		cell.setCellStyle(cellStyle2);

		CellStyle cellStyle3 = workbook.createCellStyle();
		cellStyle3.setWrapText(true);

		// text right alignment
		cellStyle3.setAlignment(HorizontalAlignment.RIGHT);
		cell = row.createCell(2);
		cell.setCellValue("This is Right Alignment");
		cell.setCellStyle(cellStyle3);

		CellStyle cellStyle4 = workbook.createCellStyle();
		cellStyle4.setWrapText(true);

		// text center alignment
		cellStyle4.setAlignment(HorizontalAlignment.CENTER);
		cell = row.createCell(3);
		cell.setCellValue("This is Center Alignment");
		cell.setCellStyle(cellStyle4);

		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 will give you the following output in the generated excel file. The excel file gets generated under project’s root directory.

text alignment in excel file java apache poi

Source Code

Download

Leave a Reply

Your email address will not be published. Required fields are marked *