Replace Field in Header&Footer in Word Using Interop

Jay picture Jay · Jul 18, 2013 · Viewed 16.2k times · Source

How to replace a "FIELD" in the header/footer?

Ex: Word doc file with File Name & Date. in place of file path - [FilePath] instead C://Documents/Location/Filename.doc ,[Date] instead 18/07/2013.

I can replace any text with range.

foreach (Microsoft.Office.Interop.Word.Section section in wordDocument.Sections)
{
   section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text.Replace(sourceDocPath, "[File Path]");

   section.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text.Replace(sourceDocPath, "[File Path]"); 
}

This works fine for The Filename, however for Date, it is not possible to guess the format to replace. This is all because I'm not able to catch the exact field info to replace.

The below code also I can't use

wordApp.Selection.Find.Execute(ref textToReplace, ref typeMissing, 
        ref typeMissing, ref typeMissing, ref typeMissing, ref typeMissing, 
        ref typeMissing, ref typeMissing, ref typeMissing, ref typeMissing, 
        ref replaceTextWith, ref replaceAll, ref typeMissing, ref typeMissing, 
        ref typeMissing, ref typeMissing);

Only way that I see as of now is handle all possible date formats and replace,but this doesn't seems like a good approach to me.

Update as per the comment given using Storyrange.

Doesn't give me the exact Field information saying [DATE].When I iterate through story range the type info I'm getting wdstorytype which is about section information, nt about the field information.

foreach (Microsoft.Office.Interop.Word.Range tmpRange in wordDocument.StoryRanges)
                    {
                        string strtype = tmpRange.StoryType.ToString();
                        tmpRange.Find.Text = "18/07/2013";
                        tmpRange.Find.Replacement.Text = "";
                        tmpRange.Find.Replacement.ParagraphFormat.Alignment =
                            Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;

                        tmpRange.Find.Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue;
                        object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;

                        tmpRange.Find.Execute(ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref replaceAll,
                            ref missing, ref missing, ref missing, ref missing);
                    }

Update: Looks something that helps me here, but doesn't seems to be working. Any idea how can i force the document object use the below before export.

field.ShowCodes = true;

Answer

Jay picture Jay · Jul 19, 2013

Finally after going through the poor documentation about introp.word, got the solution

// Loop through all sections
foreach (Microsoft.Office.Interop.Word.Section section in wordDocument.Sections) {

    wordDocument.TrackRevisions = false; //Disable Tracking for the Field replacement operation

    //Get all Headers
    Microsoft.Office.Interop.Word.HeadersFooters headers = section.Headers;

    //Section headerfooter loop for all types enum WdHeaderFooterIndex. wdHeaderFooterEvenPages/wdHeaderFooterFirstPage/wdHeaderFooterPrimary;                          
    foreach (Microsoft.Office.Interop.Word.HeaderFooter header in headers)
    {
        Fields fields = header.Range.Fields;

        foreach (Field field in fields)
        {
            if (field.Type == WdFieldType.wdFieldDate)
            {
                field.Select ();
                field.Delete ();
                wordApplication.Selection.TypeText ("[DATE]");
            }
            else if (field.Type == WdFieldType.wdFieldFileName)
            {
                field.Select ();
                field.Delete ();
                wordApplication.Selection.TypeText ("[FILE NAME]");

            }
        }
    }

    //Get all Footers
    Microsoft.Office.Interop.Word.HeadersFooters footers = section.Footers;

    //Section headerfooter loop for all types enum WdHeaderFooterIndex. wdHeaderFooterEvenPages/wdHeaderFooterFirstPage/wdHeaderFooterPrimary; 
    foreach (Microsoft.Office.Interop.Word.HeaderFooter footer in footers)
    {
        Fields fields = footer.Range.Fields;

        foreach (Field field in fields)
        {
            if (field.Type == WdFieldType.wdFieldDate)
            {
                field.Select ();
                field.Delete ();
                wordApplication.Selection.TypeText ("[DATE]");
            }
            else if (field.Type == WdFieldType.wdFieldFileName)
            {
                field.Select ();
                field.Delete ();
                wordApplication.Selection.TypeText ("[FILE NAME]");

            }
        }
    }
}