Perform Mail Merge on a Nested Merge Field inside Conditional IF Statement in Word Document using Java

Hi,

I’m evaluating Aspose.Words product and I cannot find how to use if statements with merge field. Can you please give me an example. I’ve tried to write simple if statement in Word document (like { IF { MERGEFIELD show } = true “Show” “Don’t show” } and in my Java code I’ve used document.getMailMerge().execute(keys, values); I’ve put key show and value true, but it seems that Aspose is not processing this if statement. Am I missing something?

Thank you and best regards,
Domagoj

@dmajic,

Please see TestDocs.zip (17.7 KB) and try running the following code:

Document doc = new Document("D:\\temp\\input.docx");
doc.getMailMerge().execute(new String[]{"show"}, new String[]{"true"});
doc.save("D:\\temp\\awjava-18.2.docx");

Hi Awais,

this example works. Thank you for your help!
Can you please describe the process of creating this IF statement in MS Word? When I open input.docx
file you’ve sent, I cannot edit this field. And if I try to create such field in my template it’s not working as
one you’ve sent.

Thank you and best regards,
Domagoj

@dmajic,

Insert following IF field code in first Paragraph by using MS Word:

IF “LEFT” = “true” “Show” “Dont show”

Now insert a real MERGEFIELD in second Paragraph

MERGEFIELD show

Right click on IF field and choose Toggle Field Codes. Replace LEFT of IF field with { MERGEFIELD show }.

You can also create and merge such field by using Aspose.Words for Java:

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// {IF "{MERGEFIELD show}" = "true" "Show" "Dont show"}
Field field = builder.insertField("IF \"", null);
builder.moveTo(field.getStart().getNextSibling().getNextSibling());
builder.insertField("MERGEFIELD show", null);
builder.write("\" = \"true\" \"Show\" \"Dont show\"");

doc.getMailMerge().execute(new String[]{"show"}, new String[]{"true"});

doc.save("D:\\temp\\awjava-18.2.docx");

A post was split to a new topic: Insert Nested Merge Field inside IF Field in Word Document & Execute Mail Merge using Java

A post was split to a new topic: Mail Merge Nested Merge Field inside True Part of IF Field