向 Word 文档添加页眉(Word 加载项 C#)

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

我正在尝试根据用户选择的组合框选择向 Word 文档添加 Header/Footer。

我可以让它在新文档上工作,谁能解释一下如何让它在当前活动文档上工作。

我目前的代码是:

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;
    }
}

我需要的是当点击按钮时,上面的代码运行但更新当前打开的活动文档,目前上面创建一个新文档并添加已选择的内容。

那是因为您创建了一个新文档:

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

您必须使用活动文档,您可以检索 ApplicationClass 对象:

var document = Globals.ThisAddIn.Application.ActiveDocument;