2013-12-20 63 views
1

我試圖從word文檔替換文本或合併字段。我發現我可以使用docx4j來達到這個目的。如何使用docx4j替換Ms字中的文本/合併字段

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中的稱謂合併域。請幫忙!

+0

注意變量替換(魔術字符串文件中)和郵件合併(使用Word的字段)有很大的不同。 – JasonPlutext

回答

1

請嘗試這個代碼片段:

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")); 

} 
相關問題