Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update fields in headers and footers, not just main document?

in C#, using wordDocument.Fields.Update() works great on everything in the main body.

Any suggestion for concise and elegant way to update the fields in the headers and footers as well?

like image 802
Gabe Avatar asked Aug 12 '15 12:08

Gabe


1 Answers

This one took me a bit. Had to dig a bit into the Iterop.Word documentation. Tons of examples of this in VB, but I think my code below is a good example of this in C#.

using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Office.Interop.Word;

class Program
{
    static void Main(string[] args)
    {
        List<string> path = new List<string>(args);

        string filePathstr = string.Join(" ", path.ToArray());
        //System.Windows.Forms.MessageBox.Show("filepathstr: " + filePathstr);

        string folderPathstr = Path.GetDirectoryName(filePathstr);
        //System.Windows.Forms.MessageBox.Show("folderPathstr: " + folderPathstr);

        try
        {
            Application ap = new Application();
            Document document = ap.Documents.Open(filePathstr);
            document.Fields.Update();

            foreach (Section section in document.Sections)
            {
                document.Fields.Update();  // update each section

                HeadersFooters headers = section.Headers;  //Get all headers
                foreach (HeaderFooter header in headers)
                {
                    Fields fields = header.Range.Fields;
                    foreach (Field field in fields)
                    {
                        field.Update();  // update all fields in headers
                    }
                }

                HeadersFooters footers = section.Footers;  //Get all footers
                foreach (HeaderFooter footer in footers)
                {
                    Fields fields = footer.Range.Fields;
                    foreach (Field field in fields)
                    {
                        field.Update();  //update all fields in footers
                    }
                }
            }    

            document.Save();
            document.Close();

        }
        catch (NullReferenceException)
        {
            System.Windows.Forms.MessageBox.Show("A valid file was not selected.");
        }
    }
}
like image 124
Sherd Avatar answered Oct 19 '22 09:10

Sherd