上标和下标是键入基线上方或下方的小写字母或数字。它们通常用于脚注、参考文献、数学和化学符号。本文将分享如何使用 Free Spire(适用于 Java)以编程方式在 Excel 文档中插入下标和上标.XLS。
1#下载免费的 API 并将其解压缩,然后将 Spire.Xls.jar 文件作为依赖项添加到项目中。
2#通过将以下配置添加到 pom.xml,直接将 jar 依赖项添加到 maven 项目中。
<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.free</artifactId> <version>5.1.0</version> </dependency> </dependencies>
Free Spire.XLS for Java 提供了 ExcelFont.isSubscript() 和 ExcelFont.isSuperscript() 方法,用于将字体格式化为下标和上标。然后,您可以使用 CellRange.getRichText().setFont(int startPos, int endPos, ExcelFont font) 方法将效果应用于指定的字符范围。完整的示例代码如下所示。
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 document workbook.saveToFile("SubSuperScript.xlsx", ExcelVersion.Version2016); } }