DEV Community


Apply Different Font Styles in Excel Using Java

Sharing code to help developers deal with their files in Java applications.
・2 min read

This article will share how to apply different font styles to the text in Excel cells using a 3rd party free Java API.

1# Import the Jar dependency of the free Java API
Method 1: Download the free API (Free Spire.XLS for Java)and unzip it, then add the Spire.Xls.jar file to your project as dependency.

Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

Enter fullscreen mode Exit fullscreen mode

2# Sample Code

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
        Workbook workbook = new Workbook();

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

        //Set font name
        sheet.getCellRange("B1").setText("Font name: Time New Roman");
        sheet.getCellRange("B1").getCellStyle().getExcelFont().setFontName("Time new Roman");

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

        //Set font color
        sheet.getCellRange("B3").setText("Font color: Red");

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

        //Set to underline
        sheet.getCellRange("B5").setText("Underline: Single");
        sheet.getCellRange("B6").setText("Underline: Double");

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

        //Save the result file
        workbook.saveToFile("FontStyles.xlsx", ExcelVersion.Version2016);
Enter fullscreen mode Exit fullscreen mode

3# A snapshot of the result document
Front Style

Discussion (0)