PJW
PJW

Reputation: 5417

Winforms exporting data to MS Word Merge Fields doesn't see Fields in the Header

I have a WinForms app written in C# and I use the following code to opena Word Template and export data from a SQL database into Mail Merge Fields in the Word Template.

try
{
    Object oMissing = System.Reflection.Missing.Value;
    Object oTrue = true;
    Object oFalse = false;
    Word.Application oWord = new Word.Application();
    Word.Document oWordDoc = new Word.Document();
    oWord.Visible = true;

    Object oTemplatePath = templatePath;                
    oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
    foreach (Word.Field myMergeField in oWordDoc.Fields)
    {
        Word.Range rngFieldCode = myMergeField.Code;
        String fieldText = rngFieldCode.Text;
        if (fieldText.StartsWith(" MERGEFIELD"))
        {
            Int32 endMerge = fieldText.IndexOf("\\");
            Int32 fieldNameLength = fieldText.Length - endMerge;
            String fieldName = fieldText.Substring(11, endMerge - 11);
            fieldName = fieldName.Trim();

            foreach(DataRow r in mergeFields.Rows)
            {
                if (r["MergeField"].ToString() == fieldName)
                {
                    string value = r["Value"].ToString();
                    myMergeField.Select();
                    oWord.Selection.TypeText(value);
                }
            }
        }
    }
    string fileDetails = caseFolder + "\\" + fileName + @".doc";
    oWordDoc.SaveAs2(fileDetails);
    return fileDetails;
}
catch (Exception eX)
{
    throw new Exception("Document: CreateDocument()" + Environment.NewLine + eX.Message);
}

This works fine normally. However, the latest template I have been given has Merge Fields in the document Header and embedded in a Text Box. My code, when iterating through the Merge Fields, does not see the Merge Fields in the Header or Text Box, but only those in the main body of the Word Template.

My question is, how do I revise my code to ALSO access the Merge Fields in the Header and Text Box?

Upvotes: 0

Views: 1022

Answers (1)

user3455491
user3455491

Reputation: 11

Header and Footer are in separated XML files. You can unzip docx file to tell the difference. So you not only search for document, but also for HeaderParts and FooterParts.

I create an example contains a merge field in header of the template.

Upvotes: 1

Related Questions