以编程方式向文档添加页眉和页脚

可以通过使用 SectionHeaders 属性和 Footers 属性将文本添加到文档中的页眉和页脚。 文档各部分均包含三个页眉和页脚:

文档级自定义项

若要使用以下代码示例,请从项目中的 ThisDocument 类运行它们。

将文本添加到文档的页脚

  1. 以下代码示例设置要插入到文档各部分主页脚的文本字体,然后再将文本插入页脚。

    foreach (Word.Section wordSection in this.Sections)
    {
        Word.Range footerRange = wordSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
        footerRange.Font.ColorIndex = Word.WdColorIndex.wdDarkRed;
        footerRange.Font.Size = 20;
        footerRange.Text = "Confidential";
    }
    

将文本添加到文档的页眉

  1. 以下代码示例将添加一个字段,以在文档各个页眉中显示页码,然后设置段落对齐方式,使文本对齐到页眉的右侧。

    foreach (Word.Section section in this.Sections)
    {
        Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
        headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage);
        headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
    }
    

VSTO 外接程序

若要使用以下代码示例,请从项目中的 ThisAddIn 类运行它们。

将文本添加到文档的页脚

  1. 以下代码示例设置要插入到文档各部分主页脚的文本字体,然后再将文本插入页脚。 此代码示例使用活动文档。

    foreach (Word.Section wordSection in this.Application.ActiveDocument.Sections)
    {
        Word.Range footerRange = wordSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
        footerRange.Font.ColorIndex = Word.WdColorIndex.wdDarkRed;
        footerRange.Font.Size = 20;
        footerRange.Text = "Confidential";
    }
    

将文本添加到文档的页眉

  1. 以下代码示例将添加一个字段,以在文档各个页眉中显示页码,然后设置段落对齐方式,使文本对齐到页眉的右侧。 此代码示例使用活动文档。

    foreach (Word.Section section in this.Application.ActiveDocument.Sections)
    {
        Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
        headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage);
        headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
    }