Working With Fonts

In this program we are going to make an excel sheet and set the fonts of text values, set its size.

Working With Fonts

working with fonts

     

In this program we are going to make an excel sheet and set the fonts of text values, set its size. We can also set the name of the font.

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 , org.apache.poi.hssf.usermodel. HSSFWorkbook and org.apache.poi.hssf.usermodel.HSSFFont.

org.apache.poi.hssf.usermodel.HSSFFont class extends java.lang.Object and is used to represent a font used in workbook. This also  provides various methods to set various font properties on text.
  
In this example we are using following key points:

setFontHeightInPoints((short)value):
This method is used to set the height of the text.

setFontName("Courier New"):
This method is used to set the font name.

setItalic(true):
This method is used the to set text as Italic.

setStrikeout(true):
This method is used to set strikeout on text.

setFont(font):
This method is used to set font on cell style sheet. 

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 import="org.apache.poi.hssf.usermodel.HSSFFont"%>
<%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");
  HSSFFont font = hwb.createFont();
  font.setFontHeightInPoints((short)24);
  font.setFontName("Courier New");
  font.setItalic(true);
  font.setStrikeout(true);
  HSSFCellStyle cellStyle = hwb.createCellStyle();
  cellStyle.setFont(font);
  cell.setCellStyle(cellStyle);
  FileOutputStream fileOut = new FileOutputStream
(
"c:\\excel\\fontsExcel.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.