Java/ Insert Subscript and Superscript in Excel

Superscript and subscript are characters that appear slightly above or below your regular text and are often used in mathematical as well as chemical formulas. This article will demonstrate how to insert subscript and superscript in an Excel document using Free Spire.XLS for Java.

Install Free Spire.XLS for Java
Method 1: Download the free Java library and unzip it, then add the Spire.Xls.jar file to your project as dependency.

Method 2: You can also 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>

Sample Code

Free Spire.XLS for Java offers the ExcelFont.isSuperscript() method and ExcelFont.isSubscript() method, and by setting their values to true you could apply superscript/subscript effect in an Excel document.

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 B2 and D2
sheet.getCellRange("B2").setText("An example of Subscript:");
sheet.getCellRange("D2").setText("An example of Superscript:");

//Insert text to B3 and apply subscript effect
CellRange range = sheet.getCellRange("B3");
range.getRichText().setText("R100-0.06");
ExcelFont font = workbook.createFont();
font.isSubscript(true);
font.setColor(Color.red);
range.getRichText().setFont(4, 8, font);

//Insert text to D3 and apply superscript effect
range = sheet.getCellRange("D3");
range.getRichText().setText("a2 + b2 = c2");
font = workbook.createFont();
font.isSuperscript(true);
range.getRichText().setFont(1, 1, font);
range.getRichText().setFont(6, 6, font);
range.getRichText().setFont(11, 11, font);

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

//Save the docuemnt
workbook.saveToFile("SubSuperScript.xlsx", ExcelVersion.Version2016);
}
}

Sharing Java Code