You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Apache POI在Word文档中设置上下标处于同一垂直线

Apache POI Word添加上下标对齐解决方法

在Word中用Apache POI实现上下标同垂直线对齐,核心是手动调整上下标的垂直偏移量,而非依赖默认的上下标样式。以下是具体实现方案:

关键思路

默认的上标、下标样式垂直偏移量不一致,导致无法对齐。需要在设置上下标属性的同时,手动指定Position值来统一两者的垂直位置,让它们处于同一水平线。

代码实现

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalAlign;
import java.io.FileOutputStream;
import java.math.BigInteger;

public class SubSupAlign {
    public static void main(String[] args) throws Exception {
        XWPFDocument doc = new XWPFDocument();
        XWPFParagraph para = doc.createParagraph();
        
        // 正常文本部分
        XWPFRun normalRun = para.createRun();
        normalRun.setText("H");
        
        // 上标部分:设置上标属性+手动偏移
        XWPFRun supRun = para.createRun();
        supRun.setText("2");
        supRun.getCTR().addNewRPr().addNewVertAlign().setVal(STVerticalAlign.SUPERSCRIPT);
        // 向上偏移300(单位:1/20磅,可根据字体大小微调)
        supRun.getCTR().getRPr().addNewPosition().setVal(BigInteger.valueOf(300));
        
        // 正常文本
        normalRun = para.createRun();
        normalRun.setText("O");
        
        // 下标部分:设置下标属性+手动偏移
        XWPFRun subRun = para.createRun();
        subRun.setText("2");
        subRun.getCTR().addNewRPr().addNewVertAlign().setVal(STVerticalAlign.SUBSCRIPT);
        // 向下偏移200,和上标对应调整至同一垂直线
        subRun.getCTR().getRPr().addNewPosition().setVal(BigInteger.valueOf(-200));
        
        // 保存文档
        try (FileOutputStream out = new FileOutputStream("aligned_sub_sup.docx")) {
            doc.write(out);
        }
        doc.close();
    }
}

注意事项

  • 偏移量数值是1/20磅单位,需根据你使用的字体大小微调,比如字体越大,偏移量绝对值需要相应增大。
  • 所有文本(正常、上标、下标)必须放在同一个段落内,拆分段落会导致布局错位。
  • 如果需要批量处理上下标,可以封装成工具方法,统一设置偏移量参数,避免重复代码。

内容的提问来源于stack exchange,提问作者Sharana Avali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 15:45:06