Java 如何使用docx4j在docx文档中创建样式表? 上下文
我需要生成与Microsoft Word兼容的docx文件,其中包含在Linux系统上运行的Web应用程序中的一些表。经过一些研究,我发现可以在MicrosoftWord中准备一个包含所有必需样式(段落、字符和表格)的空文档,然后用docx4j填充它 对于段落来说,它确实很好:我只需要从名称中提取样式,然后从样式中提取Java 如何使用docx4j在docx文档中创建样式表? 上下文,java,docx4j,Java,Docx4j,我需要生成与Microsoft Word兼容的docx文件,其中包含在Linux系统上运行的Web应用程序中的一些表。经过一些研究,我发现可以在MicrosoftWord中准备一个包含所有必需样式(段落、字符和表格)的空文档,然后用docx4j填充它 对于段落来说,它确实很好:我只需要从名称中提取样式,然后从样式中提取pPr属性: P p = factory.createP(); // create an empty paragraph String styleI
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创建一个表并将其影响为文档中已经存在的(表)样式?表样式的影响方式完全不同 实际上,我们不从样式中提取表属性,而是创建一个不同的对象,它是
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