Using Open Xml to Export MS Word Document

by hayrettiny 18. August 2011 11:09

If you are going to export MS Word Documents using c# .Net, Open XML is a really helpful tool. I will show you a quick tutorial.

First we need to install “Open XML SDK 2.0 Productivity Tool for Microsoft Office”. After the installation, you need to create a sample word document and style it how you would like to.

Let’s say we styled a word document like below. Just a table and has Title, Detail1, Detail2, Detail3… etc. In this tutorial I will only update the first row. (Detail1x, Detail1y)

Save this template as “temp.docx” and close the file.

Open the file with Open Xml.

Expand “[]/word/document.xml” since you can see the Table tag in document body.

 

After selecting the “<>w:tbl (Table)”  you need to click on Reflect Code button and Open Xml is going to generate a class of that table for you. That class has a “GeneratedTable()” function and return type is “DocumentFormat.OpenXml.Wordprocessing.Table “. To make this table dynamic, you can pass parameters into the “GenerateTable()” function. 

Now you can implement this template to your project.  Just you need to create a class in your project and copy generated code into that class.

Add some parameter to GenerateTable() function.

For example, I am adding two parameters which are Detail1xExplanation, and Detail1yExplanation. I will use these parameters to update the first row. You can add more parameters for the other rows.

 

 

Now, you need to find the static texts in this class and replace them with related parameters. For instance, find the “Detail1x” static text and replace it with “Detail1xExplanation” parameter.

So, you just need to create and instance and pass the values, than you will get a “DocumentFormat.OpenXml.Wordprocessing.Table” object which is already styled.

You should create another template “EmptyTemplate.docx” which has an empty table. Last thing is that you need to find that empty table and append the generated table inside of it same as below.

You are done!

Tag cloud