Partially Execute Mail Merge on few Merge Fields in Word Document using Java | Lock Merge Fields | Retain \b & \f Switches

Hello,

we have a somewhat special use case where we want to replace certain mail merge fields without excecuting mailmerge for the full document.

Simple replacing the desired fields is possible like:

String[] fieldNames = doc.getMailMerge().getFieldNames();
List<String> toReplaceFields = filterOurTargetedFields(fieldNames);

for (String fieldToReplace : toReplaceFields){
    if (!documentBuilder.moveToMergeField(fieldToReplace )) {
      LOG.error("field $curOrgField couldn't be targeted for replacement");
      continue;
    }
    documentBuilder.write(getValue(fieldToReplace));
}

But our fields could also have this “BEFORE” and “AFTER” definition:

{ MERGEFIELD company:name \b textBefore \f textAfter * MERGEFORMAT }

When using the mentioned replacement the \b and \f will be “lost”. textBefore and textAfter are gone.
Ofcoure we could just excecute mailMerge with a given field mapping as the one record but this would also excecute all merge rules like “next record” etc… and the resultion document should still be used in Word with a datasource for MailMerge.
doc.getMailMerge.execute(fNames, fValues);

Is there a way to just excecute certain fields/rules?

Thank you

@orgavision,

Please note that DocumentBuilder.moveToMergeField method just moves the cursor to a position just beyond the specified merge field and then removes the merge field. This method deletes the merge field from the document after moving the cursor. I think, you can avoid replacement of certain merge fields during Mail Merge by locking them:

Document doc = new Document("C:\\Temp\\mf.docx");

// Lock merge fields that you do not want to process
// You can also lock other types of fields like IF, NEXTIF etc that you want to preserve during mail merge
for (Field field : doc.getRange().getFields()) {
    if (field.getType() == FieldType.FIELD_MERGE_FIELD) {
        FieldMergeField mergeField = (FieldMergeField) field;
        if (mergeField.getFieldName() == "mergeField1")
            mergeField.isLocked(true);
    }
}

// In this case, executing mail merge will not have any effect on 'mergeField1'
doc.getMailMerge().execute(new String[]{"mergeField1", "mergeField2", "mergeField3"},
        new Object[]{"value1", "value2", "value3"});

// After mail merge is executed, you can then unlock above fields and may be mail merge again on remaining fields etc.

doc.save("C:\\Temp\\awjava-21.2.docx");
1 Like

Thank you for your fast reply,

this really seems to work when we lock all fields except the ones we want to replace with the mailmerge excecution.

You helped us a lot
Thanks again

@orgavision,

Thanks for your feedback. In case you have further inquiries or may need any help in future, please let us know by posting a new thread in Aspose.Words forum.