How to Add a Header to a Word Document using Microsoft Office Automation

In this tutorial, I will show how to add a header to a Microsoft Word document programmatically using C# and Microsoft Office Automation.

First, create a new project.

  • Start the Visual Studio and click on File -> New -> Project…
  • Select Console App (.NET Framework) as project type, select a location for the project and give it a name (I named it WordHeader). Click OK to create the project.
  • Next, in the Package Manager Console type Install-Package Microsoft.Office.Interop.Word and press Enter. This will install and reference the Microsoft Word library that provides functionality for access and editing of word files.

Finally, open the file Program.cs and replace its content with the following code.

using System;
using Word = Microsoft.Office.Interop.Word;

namespace WordHeader
{
    class Program
    {
        static void Main(string[] args)
        {
            Word.Application app = null;
            Word.Document doc = null;

            // Open a new Word instance
            app = new Word.Application();
            // Open or create an empty Word document
            doc = app.Documents.Add();

            // Create Header
            Word.Section section = doc.Sections[1];
            Word.HeaderFooter header = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
            header.Range.Text = "Awesome Header" + Environment.NewLine + $"Date: {DateTime.Now.ToString("dd.MM.yyyy")}";
            header.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;

            // Save the document and Quit the Word instance
            doc.SaveAs2(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\AwesomeHeader.docx");
            app.Quit();
        }
    }
}

The code opens a new instance of the Word application and add creates an empty Word document. Next, it gets access to the document’s header in the first section (the empty document has only one section) of the document. Subsequently, the code adds some text to the header and aligns it right. Finally, the code saves the document using the provided filename and quits the application instance.

If you execute the application, you will find a new Word document with the name AwesomeHeader.docx in the MyDocuments folder.

%d