Getting Open XML up and running for .NET C# Web Applications

I had to get this set up quickly on Friday for a web application that creates a Microsoft Word document on the fly and I write text to the document.¬† Just in case you need to do the same and haven’t had time to research how to do this yet, these are the exact steps I went through to get this up and running for my web application:

  1. install OpenXMLSDKV25.msi first and then install OpenXMLSDKToolV25.msi, they are here: http://www.microsoft.com/en-us/download/details.aspx?id=30425 (hit the download button and select each one)
  2. create a project in Visual Studio
  3. add this reference to your project: DocumentFormat.OpenXml
  4. add this reference to your project: WindowsBase
  5. in top of your code behind of project add this:

using System.IO;
using System.Xml;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

  • in your code behind of project, add this code (run code and you will find your new document with your text of Hello World in it):
    protected void Page_Load(object sender, EventArgs e)
    {
    HelloWorld(@”c:\test\testDocument.docx”);
    }
    public void HelloWorld(string docName)
    {
    // Create a Wordprocessing document.
    using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(docName, WordprocessingDocumentType.Document))
    {
    // Add a new main document part.
    wordDocument.AddMainDocumentPart();
    //Create the Document DOM. wordDocument.MainDocumentPart.Document = new Document( new Body( new Paragraph( new Run( new Text(“Hello World!”)))));
    // Save changes to the main document part.
    wordDocument.MainDocumentPart.Document.Save();
    }
    }

HAPPY CODING!

Blog at WordPress.com.

Up ↑