Working With Alignment Using JSP for Excel

In this program we are going to set alignment of cells on an excel sheet.

Working With Alignment Using JSP for Excel

Working with alignment using jsp for excel

     

In this program we are going to set alignment of cells on an excel sheet.

The packages we need to import are java.io.*,java.util.* ,org.apache.poi.hssf.usermodel.HSSFSheet,org.apache.poi. hssf.  usermodel. HSSFCellStyle, org.apache.poi.usermodel.HSSFRow, org.apache.poi.usermodel.HSSFCell ,and org.apache.poi.hssf.usermodel. HSSFWorkbook.

setAlignment(HSSFCellStyle.ALIGN_CENTER):
This method is used to set the alignment of cell. We first create cell style and then set the alignment to the cell. In this example we are creating cell with center alignment. But you can use other alignments.  

The code of the program is given below:

<%page import="org.apache.poi.hssf.usermodel.HSSFSheet"%>
<%page import="org.apache.poi.hssf.usermodel.HSSFWorkbook"%>
<%page import="org.apache.poi.hssf.usermodel.HSSFRow"%>
<%page import="org.apache.poi.hssf.usermodel.HSSFCell"%>
<%page import="org.apache.poi.hssf.usermodel.HSSFCellStyle"%>
<%page contentType="application/vnd.ms-excel" %>
<%page import="java.io.*" %>
<%page import="java.util.*" %>
<%
try{
  HSSFWorkbook hwb = new HSSFWorkbook();
  HSSFSheet sheet = hwb.createSheet("new sheet");
  HSSFRow row = sheet.createRow((short1);
  HSSFCell cell = row.createCell((short1);
  cell.setCellValue("rajesh");
  HSSFCellStyle cellStyle = hwb.createCellStyle();
  cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    cell.setCellStyle(cellStyle);
  FileOutputStream fileOut = new FileOutputStream
(
"c:\\excel\\aligmentExcel.xls");
  hwb.write(fileOut);
  fileOut.close();  
  out.println("Your excel file has been generated");
  
  catch Exception ex ) {
  
  }
%>

The output of the program is given below:

Download this example.