DEV Community

CodeSharing
CodeSharing

Posted on

Apply Multiple Fonts in One Cell in Java

In the previous articles, I've introduced how to apply different font styles in several different Excel cells using Free Spire.XLS for Java. Now this article will share how to apply multiple font styles in a single Excel cell by using same free API.

Import the Jar dependency
Method 1: Download the 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

Sample Code

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 first Excel font
        ExcelFont font1 = wb.createFont();
        font1.setFontName("Calibri");
        font1.setColor(Color.blue);
        font1.setSize(12f);
        font1.isItalic(true);

        //Create second Excel font
        ExcelFont font2 = wb.createFont();
        font2.setFontName("Times New Roman");
        font2.setColor(Color.BLACK);
        font2.setSize(12f);
        font2.isItalic(true);
        font2.setUnderline(FontUnderlineType.Double);

        //Create third Excel font
        ExcelFont font3 = wb.createFont();
        font3.setFontName("Arial");
        font3.setColor(Color.RED);
        font3.setSize(14f);
        font3.isBold(true);

        //Insert text to cell B5
        RichText richText = sheet.getCellRange("B5").getRichText();
        richText.setText("This is an example of how to apply multiple font styles in one Excel cell using Java.");

        //Apply three fonts to the text in the cell B5
        richText.setFont(0, 21, font1);
        richText.setFont(22, 55, font2);
        richText.setFont(56, 84, font3);

        //Save the document
        wb.saveToFile("MultiFonts.xlsx", ExcelVersion.Version2016);
    }
}
Enter fullscreen mode Exit fullscreen mode

MultiFronts

Discussion (0)