Insert Subscript and Superscript in Excel in Java

This article demonstrates how to insert subscript and superscript in an Excel document using Spire.XLS for Java.

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("This is an example of Subscript:");
        sheet.getCellRange("D2").setText("This is 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("output/SubSuperScript.xlsx", ExcelVersion.Version2016);
    }
}

Insert Subscript and Superscript in Excel in Java