Inserting Subscript in Excel with Java [Quick Guide]

Inserting Subscript in Excel using Java

Inserting subscript in Excel is a common requirement, especially when dealing with chemical formulas like CO₂, statistical footnotes, or scientific data. Using subscripts helps make data clearer and more polished, enhancing the professionalism of your documents. However, Excel’s built-in subscript feature is cumbersome and doesn’t support batch application, which can significantly slow down your workflow.

Fortunately, with the help of Java code, you can efficiently insert subscripts in Excel, freeing yourself from tedious manual work and making your tasks faster and more professional.

Preparation

Inserting a subscript in Excel using Java involves adding Java libraries. In today’s blog, we will use Spire.XLS for Java as an example to accomplish this task. Spire.XLS is a powerful Java component that works independently without relying on Microsoft Office. In addition to reading, editing, and converting Excel files, it allows users to perform advanced tasks as well.

To install it on your device, there are two options:

  1. If you are using Maven, add the following code to your pom.xml file:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls</artifactId>
        <version>15.6.3</version>
    </dependency>
</dependencies>

  1. If you prefer manual installation, download the Spire.XLS package and add the .jar file to your Java IDE.

Inserting Subscript in Excel: How to Insert New Text with Subscript

First, let’s see how to insert new text into an Excel cell with subscript formatting already applied. By setting the subscript when creating a new document, you can generate the final file directly without needing to reopen and adjust it later.

Steps—Inserting subscript in Excel when adding new text with Java:

  • Create a Workbook and get a worksheet.
  • Get a cell range using Worksheet.getCellRange() method.
  • Specify text through CellRange.getRichText().setText() method.
  • Create a font through Workbook.createFont() method.
  • Set ExcelFont.isSubscript() to true.
  • Apply the font to a text range in the cell using RichText.setFont(startIndex, endIndex, font) method.

The following code shows how to insert the text "R100-0.06" into cell B2 and set the subscript:

import com.spire.xls.*;  
  
import java.awt.*;  
  
public class InsertSubscriptNewText {  
  
    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  
        sheet.getCellRange("B2").setText("This is an example of Subscript:");  
  
        // 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);  
  
        // Auto fit column width  
        sheet.getAllocatedRange().autoFitColumns();  
  
        // Save the document  
        workbook.saveToFile("/SubscriptNewText.xlsx", ExcelVersion.Version2016);  
    }  
}

Result Preview:

Inserting Subscript in Excel with New Text Using Java

Tip: By setting ExcelFont.isSuperscript() to true, you can apply superscript to text in Excel files.

Inserting Subscript in Excel: Apply Subscript to Existing Text

Although inserting subscripts while creating a new Excel file can simplify later work, in most cases, you’ll need to deal with existing files that already contain content. This section shows you how to quickly apply subscript formatting to existing text in Excel using Java.

Steps—Inserting subscript to Excel file with existing text:

  • Create a Workbook instance and read an Excel file.
  • Get a worksheet and get the cell range.
  • Loop through cells in the cell range and find the text to apply subscript.
  • Set the text in the cell’s rich text using RichText.setText() to preserve the existing content.
  • Create a font by calling Workbook.createFont() method and configure it as Subscript by setting ExcelFont.isSubscript() to true.
  • Apply the subscript using RichText.setFont(index, index, subFont) method.

The following code demonstrates how to set subscripts for chemical formulas in the cells within the A1:A3 range:

import com.spire.xls.*;  
  
public class SubscriptExistingContent {  
  
    public static void main(String[] args) {  
        // Create a Workbook and load an Excel file  
        Workbook workbook = new Workbook();  
        // Load an Excel file  
        workbook.loadFromFile(("/test.xlsx"));  
  
        // Get a worksheet  
        Worksheet sheet = workbook.getWorksheets().get(0);  
  
        // Loop through A1:A3  
        for (int i = 1; i <= 3; i++) {  
            CellRange cell = sheet.getCellRange("A" + i);  
            String text = cell.getText();  
  
            // Find "2" in cells  
            int index = text.indexOf("2");  
            if (index != -1) {  
                // Set RichText to keep original text   
cell.getRichText().setText(text);  
  
                // Create font and set as subscript  
                ExcelFont subFont = workbook.createFont();  
                subFont.isSubscript(true);  
  
                // Apply subscript to "2"  
                cell.getRichText().setFont(index, index, subFont);  
            }  
        }  
  
        // Auto fit columns  
        sheet.getAllocatedRange().autoFitColumns();  
  
        // Save the Excel file  
        workbook.saveToFile("/SubscriptExistingContent.xlsx", ExcelVersion.Version2016);  
    }  
}  

Result Preview:

Apply Subscript to Existing Text in Excel Using Java

The above code helps us find and set the first matching character as a subscript in an existing cell. But what if the same character appears multiple times in the same cell? How can we apply subscripts to all of them at once? Let’s explore this in the next section.

Inserting Subscript in Excel: Handle Multiple Matches in a Single Cell

Using a search-and-apply method to set subscript formatting works well when there is only one instance in the cell that needs to be subscripted, such as in H₂. However, if the cell contains a chemical equation, the situation becomes more complex: there might be multiple places where subscripts are needed, along with normal numbers representing coefficients (e.g., 2H₂ + O₂ → 2H₂O). In this case, the solution is to set subscripts precisely by specifying the exact positions of the target characters in the text. Let’s take a look at the detailed steps.

Steps—Inserting multiple subscripts in Excel cells:

  • Create a Workbook object and read an Excel file.
  • Get a worksheet and a cell range.
  • Read text in the cell range and set it to rich text using CellRange.getRichText().setText() method.
  • Create a font by calling Workbook.createFont() method and configure it as subscript by setting ExcelFont.isSubscript() to true.
  • Apply subscript to specific characters with CellRange.getRichText().setFont(index, index, subFont) method.

The following code demonstrates how to set subscripts for the necessary parts of the chemical equation “2H₂ + O₂ → 2H₂O” in cell C2:

import com.spire.xls.*;  
  
public class SubscriptSpecificCell {  
  
    public static void main(String[] args) {  
        // Create a Workbook instance and load an Excel file  
        Workbook workbook = new Workbook();  
        workbook.loadFromFile(("/test.xlsx"));  
  
        // Get the first worksheet  
        Worksheet sheet = workbook.getWorksheets().get(0);  
  
        // Get a cell range  
        CellRange cell = sheet.getCellRange("C2");  
  
        // Read text from C2  
        String text = cell.getText();  
  
  
        // Set text to RichText  
        cell.getRichText().setText(text);  
  
        // Create font object and set it as subscript  
        ExcelFont subFont = workbook.createFont();  
        subFont.isSubscript(true);  
  
        // Set subscript for specific cell  
        cell.getRichText().setFont(2, 2, subFont);  
        cell.getRichText().setFont(7, 7, subFont);  
        cell.getRichText().setFont(13, 13, subFont);  
  
        // Auto fit columns  
        sheet.getAllocatedRange().autoFitColumns();  
          
        // Save the Excel file  
        workbook.saveToFile("/SubscriptSpecificCell.xlsx", ExcelVersion.Version2016);  
    }  
}

Result Preview:

Apply Subscript to Multiple Text in Excel Using Java

Conclusion

This guide provides a detailed explanation of how to set subscripts in Excel, whether you need to apply them to a single cell or a range of cells, and whether you’re formatting one instance or multiple occurrences. By the end of this page, inserting subscript in Excel will be a breeze for you. Give Spire.XLS a try and start creating professional Excel workbooks today!