Replace Field in Header&Footer in Word Using Interop

我怕爱的太早我们不能终老 提交于 2019-11-30 13:00:51

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]");

                             }
                         }
                     }
                }
Cristian

Jay,

Maybe a bit late but anyway ...

Can't comment so I answer.

Few things I though may be useful to you (or others) one day in terms of current accepted answer.

  1. To answer your question from the last Update, you can use something like this to turn on field codes and then use Find to search for fields stuff:

    wordDocument.ActiveWindow.View.ShowFieldCodes = true;
    

    So, you would turn that ON before searching (unless on already) and restore it back when you are done.

  2. The solution you provided to yourself will work for most scenarios and I used something like that for some time. However, I bumped into a document with 2000 sections. And looping through those sections will in turn loop through the same header(s) over and over again. In my case processing the document timed out (given the acceptable processing time)

  3. the solution with StoryRanges might be a better approach (combined with switching field codes)
    Some examples of using it (generic search & replace):
    http://word.mvps.org/faqs/customization/ReplaceAnywhere.htm
    https://wls.wwco.com/blog/2010/07/03/find-and-replace-in-word-using-c-net/

  4. One thing to remember: don't forget to search for things in Shapes of Range

  5. I guess you figured out how to replace the field. In any case, I am actually converting simple text to a field.

    Once Find.Execute has hit something, the range will be selected and I do

    theDoc.Fields.Add(range, WdFieldType.wdFieldDocVariable, "myDocVar");
    

TL;DR: If your documents are predictable in format and only have a small number of sections and text is not within shapes then don't worry about all this.

Akhilesh Kamate
object replaceAll = MSWord.WdReplace.wdReplaceAll;
foreach (Microsoft.Office.Interop.Word.Section section in oDoc.Sections)
{
    Microsoft.Office.Interop.Word.Range footerRange =  section.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
    footerRange.Find.Text = "Some Text";
    footerRange.Find.Replacement.Text = "Replace Text";
    footerRange.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);
}

oDoc is a "MSWord.Document" object which has current doc i.e.

oDoc = oMSWord.Documents.Open(ref "DocPath", ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

Then apply loop on "Sections" of current oDoc object. Based on "Sections" you will get range of Footer. Then you will able to find and replace the text in Footer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!