Search code examples
c#ms-wordoffice-interopribbon

Add Header to Word Document (Word Add-In C#)


I'm trying to add a Header/Footer to a word document depending on what combobox selection the user has selected.

I can get it to work on a new document, can someone explain how to get it working on the current active document.

My code at present is:

private void btnAddHeader_Click(object sender, RibbonControlEventArgs e)
{
    Microsoft.Office.Interop.Word.Document document = new Microsoft.Office.Interop.Word.Document();

    foreach (Microsoft.Office.Interop.Word.Section section in document.Sections)
    {
        Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
        headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
        headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
        headerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdRed;
        headerRange.Font.Size = 8;
        headerRange.Font.Bold = 1;
        headerRange.Font.Name = "Arial";
        headerRange.Text = cbClassification.Text;
    }
}

What I need is when the button is clicked, the above code runs but updates the current open active document, at present the above creates a new document and adds what has been selected.


Solution

  • That is simply because you create a new document:

    Microsoft.Office.Interop.Word.Document document =
        new Microsoft.Office.Interop.Word.Document();
    

    You have to use the active document, which you can retrieve the the ApplicationClass object:

    var document = Globals.ThisAddIn.Application.ActiveDocument;