Share via


ワープロ ドキュメントでヘッダーを置換する

このトピックでは、Open XML SDK for Office のクラスを使用して、ワープロ ドキュメントのヘッダーをプログラムで置き換える方法について説明します。

ヘッダー参照要素の構造

この例では、対象のファイルからヘッダー パーツを削除して、別のヘッダー パーツを作成します。 また、既存のヘッダーへの参照も削除して、新しいヘッダーへの参照を作成します。 したがって、ヘッダーおよびヘッダー参照要素に関する理解を深めておくことが役立ちます。 ISO/IEC 29500 仕様の次の情報では、ヘッダー参照要素について説明します。

headerReference (ヘッダー参照)

この要素は、ドキュメント内の現在のセクションに関連付けられる 1 つのヘッダーを指定します。 このヘッダーは、WordprocessingML パッケージ内の適切なヘッダー 部分との明示的な関係を指定する id 属性を使用して参照する必要があります。

この要素で指定されたリレーションシップの種類が https://schemas.openxmlformats.org/officeDocument/2006/header ではない場合、存在しない場合、または TargetMode 属性の値が Internal ではない場合は、ドキュメントは不適合と見なされます。

ドキュメントの各セクションには、最大で次の 3 種類のヘッダーがある可能性があります。

  • 先頭ページ ヘッダー

  • 奇数ページ ヘッダー

  • 偶数ページ ヘッダー

現在の headerReference によって指定されるヘッダーの種類は、 type 属性を介して指定されます。

特定のセクションでいずれかの種類のヘッダーが省略された場合は、以下の規則が適用されます。

  • 最初のページ ヘッダーの headerReference が指定されておらず、 titlePg 要素が指定されている場合、最初のページ ヘッダーは前のセクションから継承されるか、ドキュメントの最初のセクションである場合は、新しい空白ヘッダーが作成されます。 titlePg 要素が指定されていない場合、最初のページ ヘッダーは表示されず、奇数ページ ヘッダーはその場所で使用されます。

  • 偶数ページ ヘッダーの headerReference が指定されておらず、 evenAndOddHeaders 要素が指定されている場合、偶数ページ ヘッダーは前のセクションから継承されるか、ドキュメントの最初のセクションである場合は、新しい空白ヘッダーが作成されます。 evenAndOddHeaders 要素が指定されていない場合、偶数ページ ヘッダーは表示されず、奇数ページ ヘッダーはその場所で使用されます。

  • 奇数ページ ヘッダーの headerReference が指定されていない場合は、前のセクションから偶数ページ ヘッダーが継承されます。ドキュメントの最初のセクションである場合は、新しい空のヘッダーが作成されます。

: 次のように別々の先頭、奇数、および偶数ページ ヘッダーが定義された 3 ページのドキュメントがあるとします。

異なるヘッダーが指定された 3 ページのドキュメント

このドキュメントでは、次のパッケージング マークアップに示すように、それぞれ固有のリレーションシップ ID を持つドキュメント パーツからのリレーションシップが設定された、3 つのヘッダーが定義されています。

    <Relationships xmlns=https://schemas.openxmlformats.org/package/2006/relationships>
      …
      <Relationship Id="rId2" Type="https://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml" />
      <Relationship Id="rId3" Type="https://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header2.xml" />
      <Relationship Id="rId5" Type="https://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header3.xml" />
      …
    </Relationships>

これらのリレーションシップは、次の WordprocessingML を使用して、セクションのプロパティで参照されます。

    <w:sectPr>  
      …  
      <w:headerReference r:id="rId3" w:type="first" />  
      <w:headerReference r:id="rId5" w:type="default" />  
      <w:headerReference r:id="rId2" w:type="even" />  
      …  
    </w:sectPr>  

生成されるセクションでは、リレーションシップ ID rId3 を持つヘッダー パーツが先頭ページに、リレーションシップ ID rId2 を持つヘッダー パーツがそれ以降のすべての偶数ページに、リレーションシップ ID rId5 を持つヘッダー パーツがそれ以降のすべての奇数ページに使用されます。 例終わり]

© ISO/IEC29500: 2008.

サンプル コード

以下のコード例は、ワープロ ドキュメント内のヘッダーを別のワープロ ドキュメントのヘッダーで置換する方法を示しています。 AddHeaderFromTo メソッドを呼び出すには、次の例のようなコードを使用します。

    string filepathFrom = @"C:\Users\Public\Documents\Word15a.docx";
    string filepathTo=@"C:\Users\Public\Documents\Word15b.docx";
    AddHeaderFromTo(filepathFrom, filepathTo);

以下は、C# および Visual Basic の完全なサンプル コードです。

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.Linq;

AddHeaderFromTo(args[0], args[1]);

static void AddHeaderFromTo(string filepathFrom, string filepathTo)
{
    // Replace header in target document with header of source document.
    using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(filepathTo, true))
    using (WordprocessingDocument wdDocSource = WordprocessingDocument.Open(filepathFrom, true))
    {
        if (wdDocSource.MainDocumentPart is null || wdDocSource.MainDocumentPart.HeaderParts is null)
        {
            throw new ArgumentNullException("MainDocumentPart and/or HeaderParts is null.");
        }

        if (wdDoc.MainDocumentPart is null)
        {
            throw new ArgumentNullException("MainDocumentPart is null.");
        }

        MainDocumentPart mainPart = wdDoc.MainDocumentPart;

        // Delete the existing header part.
        mainPart.DeleteParts(mainPart.HeaderParts);

        // Create a new header part.
        DocumentFormat.OpenXml.Packaging.HeaderPart headerPart = mainPart.AddNewPart<HeaderPart>();

        // Get Id of the headerPart.
        string rId = mainPart.GetIdOfPart(headerPart);

        // Feed target headerPart with source headerPart.

        DocumentFormat.OpenXml.Packaging.HeaderPart? firstHeader = wdDocSource.MainDocumentPart.HeaderParts.FirstOrDefault();

        wdDocSource.MainDocumentPart.HeaderParts.FirstOrDefault();

        if (firstHeader is not null)
        {
            headerPart.FeedData(firstHeader.GetStream());
        }

        if (mainPart.Document.Body is null)
        {
            throw new ArgumentNullException("Body is null.");
        }

        // Get SectionProperties and Replace HeaderReference with new Id.
        IEnumerable<DocumentFormat.OpenXml.Wordprocessing.SectionProperties> sectPrs = mainPart.Document.Body.Elements<SectionProperties>();
        foreach (var sectPr in sectPrs)
        {
            // Delete existing references to headers.
            sectPr.RemoveAllChildren<HeaderReference>();

            // Create the new header reference node.
            sectPr.PrependChild<HeaderReference>(new HeaderReference() { Id = rId });
        }
    }
}