3

I am trying to replace text or merge field from word document. I found out that I could use docx4j for this purpose.

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

I've read the documentation for docx4j and some other related post such as Docx4j - How to replace placeholder with value. However,I can't seem to understand the documentation and posts properly to solve this problem.

What I need is to replace the salutation merge field in the word docx with my own salutation. Please help!

Community
  • 1
  • 1
Sujal
  • 671
  • 1
  • 16
  • 34
  • 1
    Note that variable replacement (magic strings in the document) and mail merge (using Word's fields) are very different. – JasonPlutext Sep 13 '17 at 07:45

1 Answers1

3

Please try out this code snippet :

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

}
C.Champagne
  • 5,381
  • 2
  • 23
  • 35
guest
  • 31
  • 2