Share via


[方法] Open XML API を使用して Word 2007 文書内のヘッダーを置換する

Office Open XML パッケージの仕様は、コンテンツを含み、単一のパッケージに格納されているすべてのドキュメント パーツのリレーションシップを定義する XML ファイルのセットを定義しています。これらのパッケージは、Microsoft® Office Excel® 2007、Microsoft Office PowerPoint® 2007、および Microsoft Office Word 2007 のドキュメント ファイルを構成するドキュメント パーツを結合します。Open XML API を使用して、パッケージを作成したり、パッケージを構成するファイルを操作したりできます。このトピックでは、Office Word 2007 で Office Open XML パッケージ内のヘッダーを置換するためのコードと手順について説明していますが、手順は Office Open XML 形式をサポートする 3 つのどの 2007 Microsoft Office system プログラムでも同じです。

注意

このトピックのコード サンプルは、Microsoft Visual Basic® .NET および Microsoft Visual C#® で記述されており、Microsoft Visual Studio® 2008 で作成されたアドインで使用できますVisual Studio 2008 でアドインを作成する方法の詳細については、「Open XML 形式 SDK 1.0 を使用して作業を開始する」を参照してください。

文書内のヘッダーを置換する

以下のコードでは、文書内のヘッダー パーツを削除し、外部ファイルからのカスタム XML を含む新しいドキュメント パーツに置換します。

Public Sub WDAddHeader(ByVal docName As String, ByVal headerContent As Stream)
   '  Given a document name, and a stream containing valid header content,
   '  add the stream content as a header in the document and remove the original headers.
   Const wordmlNamespace As String = "https://schemas.openxmlformats.org/wordprocessingml/2006/main"
   Const relationshipNamespace As String = "https://schemas.openxmlformats.org/officeDocument/2006/relationships"
   Dim wdDoc As WordprocessingDocument = WordprocessingDocument.Open(docName, True)

   Using (wdDoc)
      ' Delete the existing header part.
      wdDoc.MainDocumentPart.DeleteParts(wdDoc.MainDocumentPart.HeaderParts)

      '  Create a new header part.
      Dim headerPart As HeaderPart = wdDoc.MainDocumentPart.AddNewPart(Of HeaderPart)()
      Dim rId As String = wdDoc.MainDocumentPart.GetIdOfPart(headerPart)
      Dim headerDoc As XmlDocument = New XmlDocument
      headerContent.Position = 0
      headerDoc.Load(headerContent)

      '  Write the header out to its document part.
      headerDoc.Save(headerPart.GetStream)

      '  Manage namespaces to perform Xml XPath queries.
      Dim nt As NameTable = New NameTable
      Dim nsManager As XmlNamespaceManager = New XmlNamespaceManager(nt)
      nsManager.AddNamespace("w", wordmlNamespace)

      '  Get the document part from the package.
      '  Load the XML in the part into an XmlDocument instance.
      Dim xdoc As XmlDocument = New XmlDocument(nt)
      xdoc.Load(wdDoc.MainDocumentPart.GetStream)

      '  Find the node containing the document layout.
      Dim targetNodes As XmlNodeList = xdoc.SelectNodes("//w:sectPr", nsManager)
      For Each targetNode As XmlNode In targetNodes
         '  Delete any existing references to headers.
         Dim headerNodes As XmlNodeList = targetNode.SelectNodes("./w:headerReference", nsManager)
         For Each headerNode As System.Xml.XmlNode In headerNodes
            targetNode.RemoveChild(headerNode)
         Next
         '  Create the new header reference node.
         Dim node As XmlElement = xdoc.CreateElement("w:headerReference", wordmlNamespace)
         Dim attr As XmlAttribute = node.Attributes.Append(xdoc.CreateAttribute("r:id", relationshipNamespace))
         attr.Value = rId
         node.Attributes.Append(attr)
         targetNode.InsertBefore(node, targetNode.FirstChild)
      Next

      '  Save the document XML back to its document part.
      xdoc.Save(wdDoc.MainDocumentPart.GetStream(FileMode.Create))
   End Using
End Sub
public static void WDAddHeader(string docName, Stream headerContent)
{
   //  Given a document name, and a stream containing valid header content,
   //  add the stream content as a header in the document and remove the original headers.

   const string wordmlNamespace = "https://schemas.openxmlformats.org/wordprocessingml/2006/main";
   const string relationshipNamespace = "https://schemas.openxmlformats.org/officeDocument/2006/relationships";

   using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(docName, true))
   {
      // Delete the existing header part.
      wdDoc.MainDocumentPart.DeleteParts(wdDoc.MainDocumentPart.HeaderParts);

      //  Create a new header part.
      HeaderPart headerPart = wdDoc.MainDocumentPart.AddNewPart<HeaderPart>();
      string rId = wdDoc.MainDocumentPart.GetIdOfPart(headerPart);                
      XmlDocument headerDoc = new XmlDocument();
      headerContent.Position = 0;
      headerDoc.Load(headerContent);

      //  Write the header out to its document part.
      headerDoc.Save(headerPart.GetStream());

      //  Manage namespaces to perform XML XPath queries.
      NameTable nt = new NameTable();
      XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
      nsManager.AddNamespace("w", wordmlNamespace);

      //  Get the document part from the package.
      //  Load the XML in the part into an XmlDocument instance.
      XmlDocument xdoc = new XmlDocument(nt);
      xdoc.Load(wdDoc.MainDocumentPart.GetStream());

      //  Find the node containing the document layout.
      XmlNodeList targetNodes = xdoc.SelectNodes("//w:sectPr", nsManager);
      foreach (XmlNode targetNode in targetNodes)
      {
         //  Delete any existing references to headers.
         XmlNodeList headerNodes = targetNode.SelectNodes("./w:headerReference", nsManager);
         foreach (System.Xml.XmlNode headerNode in headerNodes)
         {
            targetNode.RemoveChild(headerNode);
         }

         //  Create the new header reference node.
         XmlElement node = xdoc.CreateElement("w:headerReference", wordmlNamespace);
         XmlAttribute attr = node.Attributes.Append(xdoc.CreateAttribute("r:id", relationshipNamespace));
         attr.Value = rId;
         node.Attributes.Append(attr);
         targetNode.InsertBefore(node, targetNode.FirstChild);
      }

      //  Save the document XML back to its document part.
      xdoc.Save(wdDoc.MainDocumentPart.GetStream(FileMode.Create));
   }
}

文書内のヘッダー パーツを削除して新しいドキュメント パーツに置換するには

  1. 最初に、ソース Word 2007 文書のパスと名前、および文書内の既存のヘッダーと置き換えるヘッダーを定義する XML を表すパラメータを渡します。

  2. 次に、文書を WordprocessingDocument オブジェクトとして開きます。

  3. 次に、文書内の既存のヘッダー パーツを削除し、空白のヘッダー パーツを作成します。

  4. 次に、置換ヘッダーを記述する XML の一時ホルダとなる XML ドキュメントを作成します。

    残りのコードでは、該当する名前空間に対する XPath クエリを使用して、先ほど削除したヘッダー パーツへの参照をメイン ドキュメント パーツ内で検索し、それらの参照を削除して、新しいヘッダー パーツへの参照を挿入します。

  5. 最後に、その XML は元のメイン ドキュメント パーツに保存されます。