DEV Community

CodeSharing
CodeSharing

Posted on

Apply Different Font Styles in Excel Using Java

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.

<repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
            <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
        </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls.free</artifactId>
        <version>3.9.1</version>
    </dependency>
</dependencies>
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");
        sheet.getCellRange("B2").getCellStyle().getExcelFont().setSize(20);

        //Set font color
        sheet.getCellRange("B3").setText("Font color: Red");
        sheet.getCellRange("B3").getCellStyle().getExcelFont().setColor(Color.red);

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

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

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

        //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

Top comments (0)