DEV Community

E-iceblue Product Family
E-iceblue Product Family

Posted on • Updated on

Apply Fonts in Excel Cells in Java

The ability to set fonts is one of the most basic requirements of an Excel java library. In this article, I’ll show you to how to apply font styles like size, color to cells and how to make text bold, underline or italic, by using Free Spire.XLS for Java.

Add Spire.Xls.jar as dependency

Method 1: Download Free Spire.XLS for Java pack, unzip it and you’ll get Spire.Xls.jar file from the “lib” folder. Import the jar file in your project as a dependency.

Method 2: If you are creating a Maven project, you can easily add the jar dependency by adding the following configurations to the pom.xml.

        <groupId> e-iceblue </groupId>

Example 1. Apply fonts in different cells

import com.spire.xls.ExcelVersion;
import com.spire.xls.FontUnderlineType;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

import java.awt.*;

public class SetFontStyle
    public static void main(String[] args) {

        //Create a Workbook instance
        Workbook workbook = new Workbook();

        //Get the first sheet 
        Worksheet sheet = workbook.getWorksheets().get(0);

        //Set font name 
        sheet.getCellRange("A1").setText("Font name: Comic Sans MS");
        sheet.getCellRange("A1").getCellStyle().getExcelFont().setFontName("Comic Sans MS");

        //Set font size 
        sheet.getCellRange("A2").setText("Font size: 20");

        //Set font color 
        sheet.getCellRange("A3").setText("Font color: red");

        //Set to bold 
        sheet.getCellRange("A4").setText("Font style: Bold");

        //Set to underline 
        sheet.getCellRange("A5").setText("Font style: Underline");

        //Set to italic 
        sheet.getCellRange("A6").setText("Font style: Italic");

        //Save the document 
        workbook.saveToFile("FontStyles.xlsx", ExcelVersion.Version2016);

Alt Text

Example 2. Apply multiple fonts in a signle cell

import com.spire.xls.*;

import java.awt.*;

public class ApplyMultiFontsInCell {

    public static void main(String[] args) {

        //Create a Workbook instance
        Workbook wb = new Workbook();

        //Get the first worksheet
        Worksheet sheet = wb.getWorksheets().get(0);

        //Create one Excel font
        ExcelFont font1 = wb.createFont();

        //Create another Excel font
        ExcelFont font2 = wb.createFont();
        font2.setFontName("Times New Roman");

        //Insert text to cell B5
        RichText richText = sheet.getCellRange("B5").getRichText();
        richText.setText("This document was created with Spire.XLS for Java.");

        //Apply two fonts to the text in the cell B5
        richText.setFont(0, 30, font1);
        richText.setFont(31, 50, font2);

        //Save the document
        wb.saveToFile("output/MultiFonts.xlsx", ExcelVersion.Version2016);

Alt Text

Top comments (0)