共用方式為


以程式設計方式在文件中新增頁首和頁尾

您可以使用 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;
    }