How do I format cell style in Excel document?

This example demonstrate how to use HSSFCellStyle and HSSFFont to format the cell style in excel document. Using this class we can define cell border, foreground and background color. We can also define the font we use to display the cell value.

package org.kodejava.example.poi;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;


public class ExcelCellFormat {
    public static void main(String[] args) {
        // Create an instance of workbook and sheet
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();

        // Create an instance of HSSFCellStyle which will be use to format the
        // cell. Here we define the cell top and bottom border and we also
        // define the background color.
        HSSFCellStyle style = workbook.createCellStyle();

        // We also define the font that we are going to use for displaying the
        // data of the cell. We set the font to ARIAL with 20pt in size and
        // make it BOLD and give blue as the color.
        HSSFFont font = workbook.createFont();
        font.setFontHeightInPoints((short) 20);

        // We create a simple cell, set its value and apply the cell style.
        HSSFRow row = sheet.createRow(1);
        HSSFCell cell = row.createCell(1);
        cell.setCellValue(new HSSFRichTextString("Hi there... It's me again!"));
        sheet.autoSizeColumn((short) 1);

        // Finally we write out the workbook into an excel file.
        try (FileOutputStream fos = new FileOutputStream(new File("ExcelDemo.xls"))) {
        } catch (IOException e) {

Maven Dependencies

<!-- -->

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳


    • Hi Jingah,

      Which version of Apache POI are you using? In the version 3.15 Javadoc the font.setBoldweight() method was marked as deprecated as of 3.15 beta 2 and will be removed in version 3.17.

    • Hi Alpesh,

      Can you try something like:

      DataFormat format = workbook.createDataFormat();
      HSSFCellStyle style = workbook.createCellStyle();
  1. Hello,

    I’m trying to put a formula into a cell and sometimes the formula is calculated and another times, no. The formula is concatenate several cells. When I check in Excel the Type of Cell, Excel says that is text , How can I force the cell to have the type “General”?

    Thank you very much.

    Raúl Redondo


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.