So, you want to start generating Office 2007 documents - I have good news for you - there seems to be an abundance of articles and sample code out there on the web. In this next blogpost I will show you where you need to start (as simple as possible) - for some more complex examples take a look at the links listed at the end of this posting.
Everything starts with the System.IO.Packaging namespace which lives in the WindowsBase.dll. So you will need to add a reference to this assembly. This is already where the fun starts (check out Finding WindowsBase.dll) - if you don't see WindowsBase.dll in the .Net tab - you should browse to c:\program files\reference assemblies\microsoft\framework\v3.0\WindowsBase.dll. If you have Visual Studio 2005 Extensions for .Net Framework 3.0 installed, you will probably see it directly on the .Net tab inthe Add Reference dialog box.
Next, you will probably want to install the OpenXML SDK - this will provide you with strongly typed part classes for use with Open XML documents. After installing it, add a reference to "\OpenXMLSDK\1.0.0531\lib\Microsoft.Office.DocumentFormat.OpenXml.dll". Add in the necessary using statements:
Even if you want to create an empty Word document, you are required to add in a document element in the start part document.xml as is shown in the next code snippet.
public class Generator
public void CreateEmptyDoc()
string docname = "demo.docx";
const string docxml = @"<?xml version=""1.0"" encoding=""UTF-8""
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(docname, WordprocessingDocumentType.Document))
MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
using (Stream stream = mainPart.GetStream())
byte buf = (new UTF8Encoding()).GetBytes(docxml);
stream.Write(buf, 0, buf.Length);
If you are worrying about backwards compatibility - remember that there exists a Microsoft Office Compatibility Pack which will allow Office 2000, XP and 2003 users to open 2007 documents as well.
If you want to have more information - the next articles are definitely a must read:
- ECMA Office OPEN XML - Options for Generating word documents on the server (Part I) - describes the simplest approach - embedding custom XML into Word using the Word Content Control Toolkit and content controls which are bound to the custom XML
- Building Server-Side document generation using the Open XML Object Model (MSDN - Erika Ehrli ) - Part I
- Building Server-Side document generation using the Open XML Object Model (MSDN - Erika Ehrli ) - Part II
- Generating Word documents on the Server (Part II) - Dynamically adding content controls / Structured document tags (SDT) using System.IO.Packaging API