DEV Community

E-iceblue Product Family
E-iceblue Product Family

Posted on

How to Insert Superscript and Subscript in Excel in Java

Superscript is a small letter or number typed above the baseline, while subscript is a small character or string that sits below the line of text. These two are commonly used in writing formulae, basic mathematical expressions, big numbers, footnotes, isotopes and many others.

In this article, we’re going to introduce how to apply superscript effect and subscript effect to text values in Excel documents, using Free Spire.XLS for Java.

Installing Spire.Xls.jar

If you create a Maven project, you can easily import the jar in your application using the following configurations. For non-Maven projects, download the jar file from this link and add it as a dependency in your application.

<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

Using the code

import com.spire.xls.*;

import java.awt.*;

public class InsertSubscriptSuperscript {

    public static void main(String[] args) {

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

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

        //Insert text to B3 and apply subscript effect to selected text
        CellRange range = sheet.getCellRange("B3");
        range.getRichText().setText("NH3");
        ExcelFont subscriptFont = workbook.createFont();
        subscriptFont.isSubscript(true);
        subscriptFont.setColor(Color.red);
        range.getRichText().setFont(2, 2, subscriptFont);

        //Insert text to B4 and apply superscript effect to selected text
        range = sheet.getCellRange("B4");
        range.getRichText().setText("A2 + B2 = C2");
        ExcelFont  superscriptFont = workbook.createFont();
        superscriptFont.isSuperscript(true);
        range.getRichText().setFont(1, 1, superscriptFont);
        range.getRichText().setFont(6, 6, superscriptFont);
        range.getRichText().setFont(11, 11, superscriptFont);

        //Auto fit column width 
        sheet.getAllocatedRange().autoFitColumns();

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

Alt Text

Top comments (0)