Tuesday, August 28, 2007

Tuesday, August 07, 2007

In this blog post I refers to the Microsoft SDK for Open XML Format to create Word documents with .NET code. Microsoft Office Word, Excel, PowerPoint2007 are using the Open XML format as file format. This format is based on ZIP and XML. The following example will help you to create Word documents programmatically.


Guidelines

  1. Add '\OpenXMLSDK\1.0.0531\lib\Microsoft.Office.DocumentFormat.OpenXml.dll' as reference to your Visual Studio project.
  2. Add another reference to the WindowsBase dll of the .NET 3.0 framework.
  3. Adding word document through the following code:

    // 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 content of MainDocumentPart.
    public static void SetMainDocumentContent(MainDocumentPart part)
    {
    const string docXml = @" Hello world!"

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

Tips
To create Excel sheets, you can use the SpreadsheetDocument and to create Powerpoint presentations you can use the PresentationDocument

Downloads
Microsoft SDK for Open XML Formats (Microsoft)
Open XML File Format Code Snippets for Visual Studio 2005 (Microsoft)
Office Open XML Format file creation (CodePlex)