Friday, October 10, 2025
HomeLanguagesJavaHow to Apply Fonts to the Contents of a Cell Using Java?

How to Apply Fonts to the Contents of a Cell Using Java?

In this article, we will learn how to apply the custom font and various styles associated with it using Java and Apache POI (a Java API which is very useful to handle the Microsoft Documents).

Approach:

Writing a file using POI is very simple and involve following steps:

  1. Create a workbook.
  2. Create a spreadsheet in workbook.
  3. Create a font and apply styling to it in the spreadsheet.
  4. Create a cell and apply value to it.
  5. Add cells in spreadsheet.
  6. Repeat step 3 to 5 to write more data

Example:

Java




// import Statements
import java.io.File;
import java.io.FileOutputStream;
  
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  
public class FontsInExcel {
    public static void fontFile()
    { 
          // Created a workbook
        XSSFWorkbook myWorkbook = new XSSFWorkbook();
  
        // Created a spreadsheet
        XSSFSheet newSpreadsheet
            = myWorkbook.createSheet("Book");
        XSSFRow row = newSpreadsheet.createRow(1);
  
        // Created a new font
        XSSFFont font = myWorkbook.createFont();
  
        // Setting Font Properties
        font.setFontHeightInPoints((short)30);
        font.setFontName("Arial");
        font.setBold(true);
        font.setItalic(true);
        font.setColor(HSSFColor.BRIGHT_RED.index);
  
        // Set created font into style
        XSSFCellStyle cellStyle
            = myWorkbook.createCellStyle();
        cellStyle.setFont(font);
  
        // Create a cell with a custom value and set style
        // to it.
        XSSFCell myCell = row.createCell(6);
        myCell.setCellValue("New Font");
        myCell.setCellStyle(cellStyle);
  
        // Opening and changing the File
        FileOutputStream file = new FileOutputStream(
            new File("C:/Book.xlsx"));
  
        myWorkbook.write(file);
        file.close();
    }
    public static void main(String[] args) throws Exception
    {
        fontFile();
    }
}


Output

Apply fonts to the content of a cell

RELATED ARTICLES

Most Popular

Dominic
32350 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6718 POSTS0 COMMENTS
Nicole Veronica
11880 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6838 POSTS0 COMMENTS
Ted Musemwa
7101 POSTS0 COMMENTS
Thapelo Manthata
6794 POSTS0 COMMENTS
Umr Jansen
6794 POSTS0 COMMENTS