首先,我已经创建了一个文档模板文件,并从Developer标签的XML Mapping Pane中添加了一个xml到MS Document中。
Xml用于内容绑定。
<employee>
<name></name>
</employee>
下面提到的方法用于将xml写入doc模板。该方法以documentForm(结果doc文件)、xmlSchemaFilePath(创建xml路径)、templateForm(templete文件)作为参数。
public String fillXMLBasedForm(String documentForm, String xmlSchemaFilePath, String templateForm)
throws Exception {
try {
WordprocessingMLPackage wordMLPackage = Docx4J.load(new File(templateForm));
FileInputStream xmlStream = new FileInputStream(xmlSchemaFilePath);
Docx4J.bind(wordMLPackage, xmlStream, Docx4J.FLAG_BIND_INSERT_XML);
Docx4J.save(wordMLPackage, new FileOutputStream(new File(documentForm)), Docx4J.FLAG_NONE);
}
catch(Exception e) {
e.printStackTrace();
}
return documentForm;
}
一旦我打开生成的文档文件,就会弹出 "Word发现无法读取的内容... "的对话框。
XML added via code.
<employee>
<name>Vivek Singh</name>
</employee>
下面是我用来解决这个问题的最低要求的jars。
commons-compress-1.18commons-io-2.6docx4j-core-8.1.5docx4j-JAXB-Internal-8.1.5docx4j-openxml-objects-8.1.5slf4j-api-1.7.26xalan-interpretive-8.0.0xalan-serializer-8.0.0。