Export (0) Print
Expand All
Expand Minimize
1 out of 8 rated this helpful - Rate this topic

How to: Create an Office Open XML Package by Using the Open XML API

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 create an Office Open XML 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.

NoteNote:

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.

Creating the Office Open XML Formatted Package

In the following code, you create the Office Open XML Package:

// How to create a new package as a Word document.
public static void CreateNewWordDocument(string document)
{
   using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(document, WordprocessingDocumentType.Document))
   {
      // Set the content of the document so that Word can open it.
      MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();

      SetMainDocumentContent(mainPart);
   }
}

// Set the content of MainDocumentPart.
public static void SetMainDocumentContent(MainDocumentPart part)
{
   const string docXml =
@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> 
<w:document xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
    <w:body><w:p><w:r><w:t>Hello world!</w:t></w:r></w:p></w:body>
</w:document>";

    using (Stream stream = part.GetStream())
    {
       byte[] buf = (new UTF8Encoding()).GetBytes(docXml);
       stream.Write(buf, 0, buf.Length);
    }
}

To create the Office Open XML Package

  1. First, you pass in a parameter that represents the path to and name of a Word 2007 document.

  2. Then, you create a WordprocessingDocument object representing the package based on the name of the input document.

  3. Next, the AddMainDocumentPart method is called to create a main document part as /word/document.xml in the new package.

  4. Finally, the SetMainDocumentContent method is called to populate the main document part that you just created.

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.