How to aligns cell value in excel using apache POI

This example shows you how to align the cell values using Apache POI.

To align the cell values, first you need to get the CellStyle object from workbook, you can set various property of cell using CellStyle object and set the CellStyle object to cell object.

Below is the example code.

package com.java.connect.poi;

import java.io.FileOutputStream;

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

public class POIAlignmentExample {

	public static void main(String[] args) throws Exception {
		// Create the Workbook object
		Workbook wb = new HSSFWorkbook();
		// Create a new sheet
		Sheet sheet = wb.createSheet();
		// Create a Row at line one
		Row row = sheet.createRow(1);
		// Set the height of row
		row.setHeight((short) 1000);

		createCell(wb, row, (short) 1, CellStyle.ALIGN_CENTER_SELECTION,
				CellStyle.VERTICAL_BOTTOM);
		createCell(wb, row, (short) 2, CellStyle.ALIGN_CENTER,
				CellStyle.VERTICAL_BOTTOM);
		createCell(wb, row, (short) 3, CellStyle.ALIGN_FILL,
				CellStyle.VERTICAL_CENTER);
		createCell(wb, row, (short) 4, CellStyle.ALIGN_JUSTIFY,
				CellStyle.VERTICAL_JUSTIFY);
		createCell(wb, row, (short) 5, CellStyle.ALIGN_LEFT,
				CellStyle.VERTICAL_TOP);
		createCell(wb, row, (short) 6, CellStyle.ALIGN_GENERAL,
				CellStyle.VERTICAL_CENTER);
		createCell(wb, row, (short) 7, CellStyle.ALIGN_RIGHT,
				CellStyle.VERTICAL_TOP);

		// Write the output to a file
		FileOutputStream fileOut = new FileOutputStream(
				"POIAlignmentExample.xls");
		wb.write(fileOut);
		fileOut.close();

	}

	// This method create a cell align the text
	private static void createCell(Workbook workbook, Row row, short column,
			short halign, short valign) {
		Cell cell = row.createCell(column);
		cell.setCellValue("This is example value");
		CellStyle cellStyle = workbook.createCellStyle();
		cellStyle.setAlignment(halign);
		cellStyle.setVerticalAlignment(valign);
		cell.setCellStyle(cellStyle);
	}
}