[英]How to get values from Ms word merge field using Docx4j Java
我试图在java中使用Docx4j从合并字段中检索值。 我正在使用以下方法检索word文档的所有内容:
WordprocessingMLPackage newWordMLPackage = WordprocessingMLPackage
.load(new java.io.File("C:/Users/admin/Desktop/test" + i + ".docx"));
MainDocumentPart documentPart = newWordMLPackage.getMainDocumentPart();
System.out.println(documentPart.getContent());
这将返回word文档中的内容列表。 我现在得到的是
MERGEFIELD lastName \\* MERGEFORMAT himura
我想要的是从merge- 'himura'
获取值'himura'
'。 我怎样才能做到这一点?
谢谢
您可以使用xpath执行此操作 - 请参阅方法documentPart.getJAXBNodesViaXPath(xpath, false);
我有类似的问题(想用我自己的内容替换MergeField)。 经过长时间的研究,我写了一个可以做到的方法:
private void replaceTextWithElement(MainDocumentPart mainDocumentPart, String textToReplace, Collection<Object> newElements) throws JAXBException, Docx4JException {
final String xpath = "//w:r[w:instrText[contains(text(),'MERGEFIELD') and contains(text(),'" + textToReplace + "')]]";
final List<Object> foundNodes = mainDocumentPart.getJAXBNodesViaXPath(xpath, false);
if (isEmpty(foundNodes)) {
throw new RuntimeException("Cannot find textToReplace: \"" + textToReplace + "\" in document, skipping replacement.");
}
final R r = (R)foundNodes.get(0);
final P parent = (P)r.getParent();
final int index = mainDocumentPart.getContent().indexOf(parent);
mainDocumentPart.getContent().remove(parent);
if (newElements != null) {
mainDocumentPart.getContent().addAll(index, newElements);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.