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

本文关键字:Word 加载项 文档 添加 | 更新日期: 2023-09-27 18:29:54

我正试图根据用户选择的组合框将页眉/页脚添加到word文档中。

我可以让它在新文档上工作,有人能解释如何让它在当前活动文档上工作吗。

我目前的代码是:

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

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

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

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

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

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

var document = Globals.ThisAddIn.Application.ActiveDocument;