Developing Applications with the Open XML SDK

Set Up the Environment

After installing the SDK on your development machine, create a new project and add a reference to the SDK DocumentFormat.OpenXml assembly by clicking References Add Reference. Click the .NET tab, and then select the DocumentFormat.OpenXml assembly. If you don't see the assembly in the .NET tab, you can add it manually from your installation folder.

The Open XML SDK uses .NET packaging APIs internally, so you also need to add a reference to System.IO.Packaging.Package.

Finally, add a reference to the WindowsBase assembly.

In your code, you'll want to add these three main namespaces:

DocumentFormat.OpenXml: General Open XML related functions.

DocumentFormat.OpenXml.Packaging: APIs related to packaging.

DocumentFormat.OpenXml.Wordprocessing: APIs for working on Microsoft Word (.docx) documents. The assembly also exposes namespaces for other Office client applications such as Excel and PowerPoint.

Creating a Basic Word Document

To get started, you'll create a basic Word document which will serve to show you the basic infrastructure for Word documents. Remember that an Open XML package is composed of parts (Main Document Part, Image Part, Video Part, Document Properties Part, etc.). Each part is represented by at least one file.

The WordprocessingDocument class represents a Word package. You can use the class to create a new package or open an existing package:

The various parts of the document itself are arranged hierarchically as follows:

MainDocumentPart
Document
Body
Paragraph
Run
Text

The SDK exposes classes for each of these components, which makes it simple to generate a Word document programmatically. For example, to create a document containing the text "Hello World," you walk up the hierarchy, creating the appropriate objects at each step, passing each object to the constructor of its parent object: