上下文
我需要生成Microsoft Word 兼容的 docx 文件,其中包含在 Linux 系统上运行的 Web 应用程序中的一些表。经过一些研究,我发现可以在Microsoft单词中准备包含所有必需样式(用于段落,字符和表格(的空文档,然后用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
问题
当涉及到表格样式时,不能使用它,因为tbl.setTblPr(tblPr)
需要一个TblPr
对象,而style.getTblPr
返回一个不能强制转换为TblPr
的CTTblPrBase
,并且我找不到从表格样式中提取TblPr
的方法。
问题
如何从docx4j创建一个表格,并影响文档中已经存在的(表格(样式?
表格样式受到的影响方式完全不同。
实际上,我们不是从样式中提取表属性,而是创建一个不同的对象,这是一个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