将标题添加到Word文档(Word加载项C#)

时间:2016-01-12 11:39:53

标签: c# ms-word office-interop ribbon

我正在尝试根据用户选择的组合框选择向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;
    }
}

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

1 个答案:

答案 0 :(得分:1)

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

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

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

var document = Globals.ThisAddIn.Application.ActiveDocument;
相关问题