Replace Field in Header&Footer in Word Using Interop

前端 未结 3 1942
抹茶落季
抹茶落季 2020-12-31 08:56

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/Filen

3条回答
  •  独厮守ぢ
    2020-12-31 09:28

    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.

提交回复
热议问题