【发布时间】:2014-01-09 06:16:13
【问题描述】:
我正在尝试替换 word 文档中的文本或合并字段。我发现我可以为此目的使用 docx4j。
String docxFile = "C:/Users/admin/Desktop/HelloWorld.docx";
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
.load(new java.io.File(docxFile));
HashMap<String, String> mappings = new HashMap<String, String>();
mappings.put("Hello", "salutation");
//mappings.put("salutation", "myLastname");
//mappings.put("Salutation", "myFirstName");
//mappings.put("myLastName", "Salutation");
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
// Approach 2 (original)
// unmarshallFromTemplate requires string input
String xml = XmlUtils.marshaltoString(documentPart.getJaxbElement(),
true);
// Do it...
Object obj = XmlUtils.unmarshallFromTemplate(xml, mappings);
// Inject result into docx
documentPart.setJaxbElement((Document) obj);
wordMLPackage.save(new java.io.File(
"C:/Users/admin/Desktop/OUT_SIMPLE.docx"));
我已经阅读了 docx4j 的文档和一些其他相关的帖子,例如 Docx4j - How to replace placeholder with value。但是,我似乎无法正确理解文档和帖子来解决这个问题。
我需要的是用我自己的称呼替换 docx 单词中的称呼合并字段。请帮忙!
【问题讨论】:
-
请注意,变量替换(文档中的魔术字符串)和邮件合并(使用 Word 的字段)非常不同。
标签: java docx docx4j mailmerge