如何在docx4j中添加下划线文本?

How to add underline text in docx4j?

我找不到使用 docx4j 插入下划线文本的方法。代码如下。

    WordprocessingMLPackage wordPackage = WordprocessingMLPackage.createPackage();
    MainDocumentPart mainDocumentPart = wordPackage.getMainDocumentPart();
    P p = factory.createP();
    R r =  factory.createR();
    Text t = factory.createText();
    t.setValue("Test");
    r.getContent().add(t);
    p.getContent().add(r);
    RPr rpr = factory.createRPr();
    U u = factory.createU();
    rpr.setU(u);
    r.setRPr(rpr)
    mainDocumentPart.getContent().add(p);
    File exportFile = new File("welcome.docx");
    wordPackage.save(exportFile);

我相信你不见了

u.setVal(UnderlineEnumeration.SINGLE);

在您的代码中。

请试试这个代码片段

WordprocessingMLPackage wordPackage = WordprocessingMLPackage.createPackage();
MainDocumentPart mainDocumentPart = wordPackage.getMainDocumentPart();
P p = factory.createP();
R r =  factory.createR();
Text t = factory.createText();
t.setValue("Test");
r.getContent().add(t);
p.getContent().add(r);
RPr rpr = factory.createRPr();
U u = factory.createU();
//This line here will do the trick for you.
u.setVal(UnderlineEnumeration.SINGLE);
rpr.setU(u);
r.setRPr(rpr)
mainDocumentPart.getContent().add(p);
File exportFile = new File("welcome.docx");
wordPackage.save(exportFile);