Thursday, September 06, 2007

Generating Office 2007 documents in C#

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:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Packaging;
using Microsoft.Office.DocumentFormat.OpenXml;
using Microsoft.Office.DocumentFormat.OpenXml.Packaging;

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.

namespace Dolmen.SharePoint.DocGenerator
public class Generator
public void CreateEmptyDoc()
string docname = "demo.docx";
const string docxml = @"<?xml version=""1.0"" encoding=""UTF-8""
 standalone=""yes""?><w:document xmlns:w=""""></w:document>";

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:

Technorati tags: , , , ,

1 comment:

Yaroslav Pentsarskyy said...

Here is the component that generates document based on the custom template. The documents are generated from the sharepoint list ... so the data is pulled from the list item into the document on the fly:

Hope that helps,

Yaroslav Pentsarskyy