繁体   English   中英

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

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

语境

我需要在 Linux 系统上运行的 Web 应用程序中生成包含一些表格的 Microsoft Word 兼容 docx 文件。 经过一些研究,我发现可以在 Microsoft Word 中准备包含所有必需样式(段落、字符和表格)的空文档,然后用 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); 工作原理相同,只需要找到 styleID

问题

当涉及到表格样式时,不能使用它,因为tbl.setTblPr(tblPr)需要一个TblPr对象,而style.getTblPr返回一个CTTblPrBase ,它不能转换为TblPr ,我找不到从中提取TblPr的方法一种表格样式。

如何从 docx4j 创建表格并影响它已经存在于文档中的(表格)样式?

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

事实上,我们没有从样式中提取 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM