如何使用 docx4j 在 docx 文档中创建样式 table?

How to create a styled table in a docx document with docx4j?

上下文

我需要在 Linux 系统上的 Web 应用程序 运行 中生成包含一些 table 的 Microsoft Word 兼容 docx 文件。经过一些研究,我发现可以在 Microsoft word 中准备一个包含所有必需样式(段落、字符和 tables)的空文档,然后用 docx4j 填充它。

它对段落来说真的很好用:我只需要从名称中提取样式,然后从样式中提取 pPr 属性:

P p = factory.createP();                 // create an empty paragraph
String styleId = wpMLPackage.getMainDocumentPart().getStyleDefinitionsPart()
            .getIDForStyleName(styleName);    // find the styleID because the template has defined names
PPr ppr = wpMLPackage.getMainDocumentPart().getStyleDefinitionsPart().getStyleById(styleId)
            .getPPr();                        // extract the PPr from the style
p.setPPr(ppr);                                // and affect it to the paragraph
}
R r = factory.createR();                 // finally set the paragraph text
Text txt = factory.createText();
txt.setValue(text);
r.getContent().add(txt);
p.getContent().add(r);

便捷方法wpMLPackage.getMainDocumentPart().addStyledParagraphOfText(styleId, text);的工作原理相同,只需要找到样式ID

问题

当谈到 table 样式时,不能使用它,因为 tbl.setTblPr(tblPr) 需要一个 TblPr 对象,而 style.getTblPr returns 一个 CTTblPrBase 无法转换为 TblPr,而且我找不到从 table 样式中提取 TblPr 的方法。

问题

如何从 docx4j 创建 table 并将其影响到文档中已经存在的 (table) 样式?

Table 样式以完全不同的方式受到影响。

事实上,我们并没有从样式中提取 table 属性,而是创建了一个不同的对象,即 TblStyle.

代码很简单:

    tbl = factory.createTbl();                   // create an empty table
    TblPr tblPr = factory.createTblPr();         // create a brand new TblPr
    TblStyle tblStyle = new TblStyle();          // create a brand new TblStyle
    String styleID = wpMLPackage.getMainDocumentPart().getStyleDefinitionsPart()
            .getIDForStyleName(styleName));      // find the style ID from the name
    tblStyle.setVal(styleID);                    // just tell tblStyle what style it shall be
    tblPr.setTblStyle(tblStyle);                 // and affect each object its property...
    this.tbl.setTblPr(tblPr);
    wpMLPackage.getMainDocumentPart().getContent().add(tbl);   // we can now add the styled table