This documentation is archived and is not being maintained.

How to: Copy the Contents of an Office Open XML Package Part to a Document Part in a Different Package by Using the Open XML API

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

The Office Open XML Package specification defines a set of XML files that contain the content and define the relationships for all of the document parts stored in a single package. These packages combine the parts that comprise the document files for Microsoft® Office Excel® 2007, Microsoft Office PowerPoint® 2007, and Microsoft Office Word 2007. The Open XML Application Programming Interface (API) allows you to create packages and manipulate the files that comprise the packages. This topic walks through the code and steps to copy the contents of an Office Open XML document part to a document part in a different package in Word 2007, although the steps are the same for each of the three 2007 Microsoft Office system programs that support the Office Open XML Format.


The code samples in this topic are in Microsoft Visual Basic® .NET and Microsoft Visual C#®. You can use them in an add-in created in Microsoft Visual Studio® 2008. For more information about how to create an add-in in Visual Studio 2008, see Getting Started with the Open XML Format SDK 1.0.

In the following code, you copy the contents of one document part in an Open XML package to a document part in a different package:

// How to copy contents of one package part.
public static void CopyThemeContent(string fromDocument1, string toDocument2)
   using (WordprocessingDocument wordDoc1 = WordprocessingDocument.Open(fromDocument1, false))
   using (WordprocessingDocument wordDoc2 = WordprocessingDocument.Open(toDocument2, true))
      ThemePart themePart1 = wordDoc1.MainDocumentPart.ThemePart;
      ThemePart themePart2 = wordDoc2.MainDocumentPart.ThemePart;

       using (StreamReader streamReader = new StreamReader(themePart1.GetStream()))
       using (StreamWriter streamWriter = new StreamWriter(themePart2.GetStream(FileMode.Create))) 
         streamWriter.Write( streamReader.ReadToEnd() );

To copy the contents of a document part in an Open XML package to a document part in a different package

  1. First, you pass in parameters representing the path to and name of the source Word 2007 document and the target Word 2007 document.

  2. Then, you open each of the documents as WordprocessingDocument objects.

  3. Next, you create variables that reference the ThemePart parts in each of the packages.

  4. Finally the contents of the source ThemePart part is read by using a StreamReader object and written to the target ThemePart part by using a StreamWriter object.