How to Align Text in Excel Cells Using Java

Aligning text in Excel can adjust how text fits in the cell. This article will introduce how to use Free Spire.XLS for Java to set a range of alignment options, such as horizontal and vertical alignments, the text orientation and indentation.

Installation (2 Method)
1# Download the Free Spire.XLS for Java and unzip it, then add the Spire.Xls.jar file to your project as dependency.

2# You can also add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls.free</artifactId>
<version>3.9.1</version>
</dependency>
</dependencies>

Sample Code

import com.spire.xls.*;

public class AlignText {
public static void main(String[] args){
//Create a workbook
Workbook workbook = new Workbook();

//Load an Excel file
workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");

//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);

//Set the vertical alignment to Top
sheet.getCellRange("B1").getCellStyle().setVerticalAlignment(VerticalAlignType.Top);
//Set the vertical alignment to Center
sheet.getCellRange("B2").getCellStyle().setVerticalAlignment(VerticalAlignType.Center);
//Set the vertical alignment to Bottom
sheet.getCellRange("B3").getCellStyle().setVerticalAlignment(VerticalAlignType.Bottom);

//Set the horizontal alignment to General
sheet.getCellRange("B4").getCellStyle().setHorizontalAlignment(HorizontalAlignType.General);
//Set the horizontal alignment to Left
sheet.getCellRange("B5").getCellStyle().setHorizontalAlignment(HorizontalAlignType.Left);
//Set the horizontal alignment to Center
sheet.getCellRange("B6").getCellStyle().setHorizontalAlignment(HorizontalAlignType.Center);
//Set the horizontal alignment to Right
sheet.getCellRange("B7").getCellStyle().setHorizontalAlignment(HorizontalAlignType.Right);

//Set the text orientation by using setRotation method
sheet.getCellRange("B8").getCellStyle().setRotation(45);
sheet.getCellRange("B9").getCellStyle().setRotation(90);

//Set the text indentation
sheet.getCellRange("B10").getCellStyle().setIndentLevel(6);

//Set the text direction
sheet.getCellRange("B11").getCellStyle().setReadingOrder(ReadingOrderType.LeftToRight);

//Set the row height
sheet.getCellRange("B8").setRowHeight(60);
sheet.getCellRange("B9").setRowHeight(60);

//Save the result file
workbook.saveToFile("AlignText.xlsx", ExcelVersion.Version2010);
}
}

Sharing Java Code