Replace existing bookmark with DB data

We have an application that merges data from a DB into a word document…The bookmarks are in this format {Form_0001_Item_001 *MERGEFORMAT} where Form_0001 and Item_001 identifies the DB field…
The app creates an instance of word using m_WordDoc = m_WordApp.Documents.Open

We use

foreach (Field WordDocField in (m_WordDoc.Fields)
{
    sBookmarkName = WordDocField.Code.Text.Trim();
    if (sBookmarkName.EndsWith("\\*MERGEFORMAT") == false)

to find each bookmark…then use

WordRange.Text = sFieldValue;

to replace the {Form_0001_Item_001 *MERGEFORMAT} with the data…

How can this be done with Aspose.Words?

We also expand rows in tables based on the number of db items…tables start with one row and are expanded to have the number of rows to match the data…

@rturocy

You can use Mail Merge or LINQ Reporting engine to achieve your requirement. You need to create template document for mail merge or LINQ Reporting.

Please read the following articles about mail merge.
https://docs.aspose.com/words/net/mail-merge-template
https://docs.aspose.com/words/net/types-of-mail-merge-operations/

Regarding LINQ Reporting, please read following articles.
https://docs.aspose.com/words/net/linq-reporting-engine-api/
https://docs.aspose.com/words/net/template-syntax/
https://docs.aspose.com/words/net/linq-reporting-engine-or-mail-merge/

Thank you for your quick response…Is there an example the code that would be need to replace the bookmarks created in the first example (create template) with actual data?

Our existing templates use the bookmark formatted as {Form_0001_Item_001 *MERGEFORMAT} where Form_0001 and Item_001 identifies the DB field…

Will we need to change all the templates to use a different bookmark format? If so what do you suggest…

If we can keep our existing bookmark format…can we use doc.MailMerge.Execute(Form_0001_Item_001, “ABC”) to replace the bookmark with ABC?

@rturocy

You can get the code examples from Aspose.Words GitHub repository from here:
https://github.com/aspose-words/Aspose.Words-for-.NET

Could you please ZIP and attach your input Word document here for our reference? We will then provide you template document and code example according to your requirement.

What happens if doc.MailMerge.Execute(fieldNames, fieldValues); is used and fieldNames contains items that are not a bookmark in the template? Are they ignored or would it be considered an error?

the attached zip file contains two sample templates…RichSampleTemplates.zip (66.5 KB)

@rturocy

We suggest you please convert the fields in your document e.g. { Form_0002_Item_001 *MERGEFORMAT } into mail merge fields.

Following code example inserts mail merge fields into Word document and replace them with their values. You can manually replace the current fields in your document using MS Word with mail merge fields. You can do the same using Aspose.Words.

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

builder.InsertField(" MERGEFIELD FullName ");
builder.InsertParagraph();
builder.InsertField(" MERGEFIELD Company ");
builder.InsertParagraph();
builder.InsertField(" MERGEFIELD Address ");
builder.InsertParagraph();
builder.InsertField(" MERGEFIELD City ");

doc.MailMerge.Execute(new string[] { "FullName", "Company", "Address", "City" },
    new object[] { "James Bond", "MI5 Headquarters", "Milbank", "London" });

doc.Save(ArtifactsDir + "MailMerge.docx");

@rturocy

Following code example shows how to replace the fields in your document with mail merge fields. Hope this helps you.

Document doc = new Document(MyDir + "{2F452457-2698-411B-A380-D115787C8C91}.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
foreach (Field field in doc.Range.Fields.ToArray<Field>())
{
    if (field.GetFieldCode().Contains(@"\*MERGEFORMAT"))
    {
        var fieldname = field.GetFieldCode().Substring(0, field.GetFieldCode().IndexOf(" "));
        builder.MoveToField(field, false);
        builder.InsertField(" MERGEFIELD " + fieldname + " ");
        field.Remove();
    }
}
doc.Save(MyDir + "output.docx");

Thanks…

Once the fields are converted to mail merge fields…

If we have an array for fieldNames that contains all the fields from the DB table what happens if doc.MailMerge.Execute(fieldNames, fieldValues); is used and fieldNames contains items that are not a bookmark in the template? Are they ignored or would it be considered an error?

@rturocy

Yes, the database fields are merged with their values. In your case, we suggest you please use [MailMerge.Execute method (DataTable)]https://reference.aspose.com/words/net/aspose.words.mailmerging/mailmerge/execute/. You can pass DataTable to MailMerge.Execute method to perform mail merge from a DataTable into the document.

Please read mail merge articles suggested in this thread.

My question was what if I pass a field and value to the MailMerge.Exceute function that is not on the template…What happens…Is it ignored or is it an error?

Here is our process…User create electronic forms which can contain many fields…Users also create a word document template that can contain all of the fields but more often the template contains a subset of the fields on the electronic form…Our current program loads all of the fields and their values into hashtables in c#…the program then opens the template with a word instance and loops thru the fields on the form looking for the *MERGEFORMAT and does a lookup in the hashtable for field name and replaces the word *MERGEFORMAT field with the value…

My question is what happens if we pass to the MailMerge.Execute function field names that do not exist in the word template? Are they ignored or do they cause an error? I would like to just pass the complete field names hashtable and value tables without having to first loop through the word template to find the field names that are used in the template…

I am planning on using your suggestion of converting our *MERGEFORMAT fields into MERGEFIELD fields…

@rturocy

Yes, these fields are ignored. The unmerged fields remains as it in the output document. You can remove these fields from the document using mail merge engine. Please refer to the following article.
https://docs.aspose.com/words/net/clean-up-before-or-during-mail-merge/

Yes, the field names that do not exist in the word template are ignored. Please install the latest version of Aspose.Words for .NET and execute following code example to check your scenario. You can rename the table’s field name to test your case.

DataTable table = new DataTable("Test");
table.Columns.Add("CustomerName");
table.Columns.Add("Address");
table.Rows.Add(new object[] { "Thomas Hardy", "120 Hanover Sq., London" });
table.Rows.Add(new object[] { "Paolo Accorti", "Via Monte Bianco 34, Torino" });

// Below are two ways of using a DataTable as the data source for a mail merge.
// 1 -  Use the entire table for the mail merge to create one output mail merge document for every row in the table:
Document doc = CreateSourceDocExecuteDataTable();

doc.MailMerge.Execute(table);

doc.Save(MyDir + "MailMerge.ExecuteDataTable.WholeTable.docx");

// 2 -  Use one row of the table to create one output mail merge document:
doc = CreateSourceDocExecuteDataTable();

doc.MailMerge.Execute(table.Rows[1]);

doc.Save(MyDir + "MailMerge.ExecuteDataTable.OneRow.docx");
private static Document CreateSourceDocExecuteDataTable()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.InsertField(" MERGEFIELD CustomerName ");
    builder.InsertParagraph();
    builder.InsertField(" MERGEFIELD Address ");

    return doc;
}

Please get the 30 days temporary license and apply it before using above code example.