[英]How to replace text/Merge field in Ms word with docx4j
我正在嘗試從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-如何用value替換占位符 。 但是,我似乎無法正確理解文檔和帖子來解決此問題。
我需要用自己的稱呼替換docx一詞中的稱呼合並字段。 請幫忙!
請嘗試以下代碼片段:
public static void main(String[] args) throws Exception {
String docxFile = "template.docx";
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(docxFile));
List<Map<DataFieldName, String>> data = new ArrayList<Map<DataFieldName, String>>();
Map<DataFieldName, String> item = new HashMap<DataFieldName, String>();
item.put(new DataFieldName("@name"), "myFirstname");
item.put(new DataFieldName("@lastname"), "myLastname");
data.add(item);
org.docx4j.model.fields.merge.MailMerger.setMERGEFIELDInOutput(OutputField.KEEP_MERGEFIELD);
org.docx4j.model.fields.merge.MailMerger.performMerge(wordMLPackage, item, true);
wordMLPackage.save(new java.io.File("OUT.docx"));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.