Using XSLT and Open XML to Create a Word 2007 Document
Summary: Learn how to transform XML data into a Word 2007 document by starting with an existing document that has the desired layout. (12 Printed Pages)
Applies to:2007 Microsoft Office system, Microsoft Office Word 2007, Microsoft Visual Studio 2008, Open XML Software Development Kit 2.0 for Microsoft Office
Michael Case, iSoftStone
December 2009
You can use XSL Transformations (XSLT) to transform XML data into the Open XML SDK 2.0 for Microsoft Office format that Microsoft Office Word 2007 uses, and create Word 2007 documents from XML data. To make it simpler to transform XML data into a Word 2007 document, start with an existing Word 2007 document that has the desired layout. This Visual How To shows how to use XSLT to create a Word 2007 document. It shows how to create an XSL Transform file that is based on an existing Word 2007 document. The code sample shows how to use the XSL Transform file to create a Word 2007 document that is based on data that is stored in an XML file. You must install the Open XML SDK 2.0 for Microsoft Office to follow the steps in this Visual How To. |
Length: 08:09 | Size: 10.06 MB | Type: WMV file |
Code It | Read It | Explore It
Code It
This Visual How To shows how to create a Windows C# console application that takes an XML data file, an XSL Transform file, and a Word 2007 document template, and then uses XSLT to create a well- formatted Word 2007 document that contains the data from the XML data file.
To illustrate how to create the solution described earlier, this section walks through the following steps:
Creating an XML data file.
Creating a Word 2007 template document that has the desired layout.
Extracting the contents of the main document part of the Word 2007 template document.
Creating an XSL Transform file that is based on the extracted content.
Adding Transforms to the XSL Transform file.
Creating a Windows console application solution in Visual Studio 2008.
Adding references to the required assemblies to the Visual Studio solution.
Adding code to the Visual Studio solution that creates a new Word 2007 document that uses the XML data and XSL Transform files.
Creating an XML Data File
The sample code for this Visual How To specifies that a personal movie library XML data file named MyMovies.xml exists in the C:\Temp directory.
To create the MyMovies.xml data source
Start Visual Studio 2008.
From the File menu, point to New and then click File.
In the New File dialog box, select XML File.
Copy the following XML example into the new file.
<?xml version="1.0" encoding="UTF-8"?>
<Movies>
<Genre name="Action">
<Movie>
<Name>Crash</Name>
<Released>2005</Released>
</Movie>
</Genre>
<Genre name="Drama">
<Movie>
<Name>The Departed</Name>
<Released>2006</Released>
</Movie>
<Movie>
<Name>The Pursuit of Happyness</Name>
<Released>2006</Released>
</Movie>
</Genre>
<Genre name="Comedy">
<Movie>
<Name>The Bucket List</Name>
<Released>2007</Released>
</Movie>
</Genre>
</Movies>Save the document as C:\Temp\MyMovies.xml.
Creating a Word 2007 Template Document
The sample code uses an existing Word 2007 document to help simplify the creation of the XSL Transform file. The code specifies that a Word 2007 document named MyMoviesTemplate.docx is in the C:\Temp directory.
To create the MyMoviesTemplate.docx document
Start Word 2007.
Add text to the document and placeholders for the XML data following the layout in the example. The placeholders in the document shown in this section are Genre Name, Movie Title, and year. When the code performs the XSL transform, these are replaced with data that is pulled from the XML data file that you created earlier.
Figure 1. Word 2007 Template DocumentSave the document as C:\Temp\MyMoviesTemplate.docx.
Extracting the Contents of the Main Document Part of the Template Document
To simplify the creation of the XSL Transform file, use the contents of the Word 2007 template document that you created in the previous step as a starting point. Word 2007 documents use the Open Packaging Conventions (OPC). This means that Word documents are really .zip files that contain XML, binary, and other kinds of files. By adding the .zip extension to the end of the Word 2007 document name, you can then use tools such as WinZip or Windows Explorer to examine and extract the contents of the document.
To create the XSL Transform file, the Word 2007 template document that you created earlier is temporarily renamed with a .zip extension. The document.xml file is then extracted from the template document to the C:\Temp directory, renamed to MyMovies.xslt and converted from XML to XSLT.
To extract the contents of the main document part of the template document
Start Windows Explorer and navigate to the folder that contains the MyMoviesTemplate.docx file that you created earlier.
Rename MyMoviesTemplate.docx to MyMoviesTemplate.docx.zip to gain access to the underlying Open XML files.
Use Windows Explorer to explore the contents of the MyMoviesTemplate.docx ZIP file. Navigate to the Word folder in the .zip file and copy the document.xml file to the C:\Temp folder and rename the file to MyMovies.xslt.
Figure 2. Copying the Document.XML FileRename MyMoviesTemplate.docx.zip back to MyMoviesTemplate.docx.
Creating an XSL Transform File Based on the Extracted Content
The next step is to convert the MyMovies.xslt file to an XSL Transform file.
To create the MyMovies.xslt XSL transform file
In Visual Studio 2008, open the MyMovies.xslt that you created in the previous step.
Do the following to convert the document structure of MyMovies.xslt from XML to XSLT:
Remove the following line from the top of the document.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>Add the following line to the top of the document.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">Close the style sheet element by adding the following line to the very end of the document.
</xsl:stylesheet>Add an <xsl:template> element around the existing <w:document> element.
<xsl:template match="/">
<w:document ...>
<w:body>
...
</w:body>
</w:document>
</xsl:template>Save the changes to the MyMovies.xslt file.
Adding Transforms to the XSL Transform File
In the next step, you add XSL Transform elements to list the name of each genre and information for each movie within the genre in the XML data file. This transform uses the xsl:value-of and xsl:for-each elements.
Use the xsl:value-of elements to replace the Genre Name, Movie Title, and (year) placeholders in the Word 2007 template document.
Use two xsl:for-each elements to list each genre and its movies. When you place the xsl:for-each elements, make sure that you include all Open XML elements related to the genre or movie text you repeat to ensure that valid Open XML format is output by the transformation.
The following example is a fragment from the contents of the original document.xml. It shows the placeholder text from the template document.
...
<w:p w:rsidR="00EC137C" w:rsidRPr="00BF ...
<w:pPr>
<w:pStyle w:val="Heading2"/>
</w:pPr>
<w:r w:rsidRPr="00BF350E">
<w:t>Genre Name</w:t>
</w:r>
</w:p>
<w:p w:rsidR="00EC137C" w:rsidRPr="00EC1 ...
<w:pPr>
<w:pStyle w:val="ListParagraph"/>
<w:numPr>
<w:ilvl w:val="0"/>
<w:numId w:val="1"/>
</w:numPr>
</w:pPr>
<w:r w:rsidRPr="00BF350E">
<w:rPr>
<w:b/>
</w:rPr>
<w:t>Movie Title</w:t>
</w:r>
<w:r w:rsidR="00C46B60">
<w:t xml:space="preserve"> (year)</w:t>
</w:r>
</w:p>
...
The following example is an XSLT fragment of the modified MyMovies.xslt file. It shows the changes that were made to include the XSL Transform elements.
<!-- for-each loop added for Genre. This loop includes the Open XML elements for the paragraph the Genre placeholder is in and all paragraphs for the Movies. -->
<xsl:for-each select="Movies/Genre">
<w:p w:rsidR="00EC137C" w:rsidRPr="00BF ...
<w:pPr>
<w:pStyle w:val="Heading2"/>
</w:pPr>
<w:r w:rsidRPr="00BF350E">
<w:t>
<!-- Genre Name placeholder replaced by the Genre's Name attribute in the XML data file. -->
<xsl:value-of select="@name"/>
</w:t>
</<xsl:value-of select w:r>
</w:p>
<!-- for-each loop added for Movie. This loop includes the Open XML elements that define the paragraph as a bulleted list. -->
<xsl:for-each select="Movie">
<w:p w:rsidR="00EC137C" w:rsidRPr="00EC1 ...
<w:pPr>
<w:pStyle w:val="ListParagraph"/>
<w:numPr>
<w:ilvl w:val="0"/>
<w:numId w:val="1"/>
</w:numPr>
</w:pPr>
<w:r w:rsidRPr="00BF350E">
<w:rPr>
<w:b/>
</w:rPr>
<w:t>
<!-- Movie Title placeholder replaced by the Movie's Name element in the XML data file. -->
<xsl:value-of select="Name"/>
</w:t>
</w:r>
<w:r w:rsidR="00C46B60">
<!-- Year placeholder replaced by the Movie's Released element in the XML data file. -->
<w:t xml:space="preserve"> (<xsl:value-of select="Released"/>)
</w:t>
</w:r>
</w:p>
</xsl:for-each>
</xsl:for-each>
...
Be sure that you save the modified MyMovies.xslt file after you make any changes.
Creating a Console Application in Visual Studio 2008
This Visual How To uses a Windows console application as the framework for the sample code. The console application type was selected only for its simplicity. Other application types could use the same approach presented here.
To create a Windows console application in Visual Studio 2008
Start Microsoft Visual Studio 2008.
From the File menu, point to New and then click Project.
In the New Project dialog box select the Visual C# Windows type in the Project types pane.
In the Templates pane, select Console Application.
Name the project and solution XSLTWordDocument.
Figure 3. Creating the SolutionClick OK to create the solution.
Adding References to Required Assemblies
This Visual How To uses the strongly typed classes that are provided with the Open XML SDK 2.0 to access content in a Word 2007 document. You must install the Open XML SDK 2.0 before completing the following steps.
To add a Reference to the OpenXml Assemblies
From the Visual Studio Project menu, click Add Reference.
On the .NET tab, select the DocumentFormat.OpenXml assembly and then click OK to add the reference.
On the .NET tab, add a reference to the WindowsBase assembly.
Adding the Sample Code to the Solution
Replace the contents of the Program.cs source file with the following example.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.IO;
using System.Xml;
using System.Xml.Xsl; using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing; namespace XSLTWordDocument
{
class Program
{
/// <summary>
/// This application uses the xslt file created from the
/// original Word 2007 template document to transform xml data
/// into a valid Open XML 2.0 Wordprocessing format.
/// The application then updates the output document with the
/// new content using the Open XML SDK version 2.0.
/// </summary>
static void Main(string[] args)
{
//Declare variables for file locations.
string rootPath = @"C:\Temp";
string xmlDataFile = rootPath + @"\MyMovies.xml";
string xsltFile = rootPath + @"\MyMovies.xslt";
string templateDocument = rootPath + @"\MyMoviesTemplate.docx";
string outputDocument = rootPath + @"\MyMovies.docx"; //Create a writer for the output of the Xsl Transformation.
StringWriter stringWriter = new StringWriter();
XmlWriter xmlWriter = XmlWriter.Create(stringWriter); //Create the Xsl Transformation object.
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(xsltFile); //Transform the xml data into Open XML 2.0 Wordprocessing format.
transform.Transform(xmlDataFile, xmlWriter); //Create an Xml Document of the new content.
XmlDocument newWordContent = new XmlDocument();
newWordContent.LoadXml(stringWriter.ToString()); //Copy the Word 2007 source document to the output file.
System.IO.File.Copy(templateDocument, outputDocument, true); //Use the Open XML SDK version 2.0 to open the output
// document in edit mode.
using (WordprocessingDocument output =
WordprocessingDocument.Open(outputDocument, true))
{
//Using the body element within the new content XmlDocument
// create a new Open Xml Body object.
Body updatedBodyContent =
new Body(newWordContent.DocumentElement.InnerXml); //Replace the existing Document Body with the new content.
output.MainDocumentPart.Document.Body = updatedBodyContent; //Save the updated output document.
output.MainDocumentPart.Document.Save();
}
}
}
}
The sample code shown here takes the Word 2007 template document, the XSL Transform file that was created from the Word 2007 template document, and the XML data file, and then creates a new Word 2007 document that contains the XML data. The solution uses the XSL Transform file to transform the XML data into the Open XML format. The Open XML SDK 2.0 is then used to create a new Word 2007 document that contains the new content.
Read It
Starting with a Word 2007 document that already contains the layout makes it easy for you to create a Word 2007 document that contains XML data. Once you create the Word 2007 document, you can extract the contents and XSLT elements that you added to replace values or to repeat information.
The sample code in this Visual How To transforms XML data into the Open XML Wordprocessing format by using an XSL Transform file that was created from a template Word 2007 document. The Open XML SDK 2.0 is then used to create a new Word 2007 document that has content based on the XML data.
The following example shows the transformation of XML data into the Open XML Wordprocessing format. The code uses anXslCompiledTransform object to load the XSLT and calls its Transform method to transform the XML data. The results of the transformation are then loaded into an XmlDocument object.
//Create a writer for the output of the Xsl Transformation.
StringWriter stringWriter = new StringWriter();
XmlWriter xmlWriter = XmlWriter.Create(stringWriter); //Create the Xsl Transformation object.
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(xsltFile); //Transform the xml data into Open XML 2.0 Wordprocessing format.
transform.Transform(xmlDataFile, xmlWriter); //Create an Xml Document of the new content.
XmlDocument newWordContent = new XmlDocument();
newWordContent.LoadXml(stringWriter.ToString());
The following example shows the creation of the output Word 2007 document and then opening it for editing by using the Open XML SDK 2.0. First the template document is copied to a new file. Then, the WordprocessingDocument class is used to open the document in edit mode.
//Copy the Word 2007 template document to the output file.
System.IO.File.Copy(templateDocument, outputDocument, true); //Use the Open XML SDK version 2.0 to open the output
// document in edit mode.
using (WordprocessingDocument output =
WordprocessingDocument.Open(outputDocument, true))
{
The following example shows the use of the Open XML SDK 2.0 to modify the output Word 2007 document. It uses a Body object to update the Word 2007 document's content to the results of the transformation shown previously. The root element of the transformation results is aw:document element, which contains the w:body element that is needed to create a Body object. To create the Body object the w:body element of the transformation is used.
//Using the body element within the new content XmlDocument
// create a new Open Xml Body object.
Body updatedBodyContent =
new Body(newWordContent.DocumentElement.InnerXml); //Replace the existing Document Body with the new content.
output.MainDocumentPart.Document.Body = updatedBodyContent; //Save the updated output document.
output.MainDocumentPart.Document.Save();
Using XSLT and Open XML to Create a Word 2007 Document的更多相关文章
- Embedding Documents in Word 2007 by Using the Open XML SDK 2.0 for Microsoft Office
Download the sample code This visual how-to article presents a solution that creates a Word 2007 doc ...
- User Word Automation Services and Open XML SDK to generate word files in SharePoint2010
SharePoint 2010 has established a new service called "Word Automation Services" to operate ...
- C# 读写xml、excel、word、ppt、access
C# 读写xml.excel.word.access 这里只是起个头,不做深入展开,方便以后用到参考 读写xml,主要使用.net 的xml下的document using System;using ...
- asp.net导出excel-一行代码实现excel、xml、pdf、word、html、csv等7种格式文件导出功能而且美观-SNF快速开发平台
分享: 腾讯微博 新浪微博 搜狐微博 网易微博 腾讯朋友 百度贴吧 豆瓣 QQ好友 人人网 作者:王春天 原文地址:http://www.cnblogs.com/spring_ ...
- XML Parser Errors See Details for more Information XML Parser Error on line 1: Document root ele
1.错误描写叙述 XML Parser Errors See Details for more Information XML Parser Error on line 1: Document roo ...
- C# : 操作Word文件的API - (将C# source中的xml注释转换成word文档)
这篇博客将要讨论的是关于: 如何从C#的source以及注释, 生成一份Word格式的关于各个类,函数以及成员变量的说明文档. 他的大背景如下...... 最近的一个项目使用C#, 分N个模块, 在项 ...
- java对word文档的操作(提取标题和内容等)-直接操作或poi工具包或freemarker+xml或html转word
1,java自带工具包实现对word的排版和写入 import java.awt.Color; import java.io.FileNotFoundException; import java.io ...
- Freemarker + xml 实现Java导出word
前言 最近做了一个调查问卷导出的功能,需求是将维护的题目,答案,导出成word,参考了几种方案之后,选择功能强大的freemarker+固定格式之后的wordxml实现导出功能.导出word的代码是可 ...
- Adding Form Fields to a MS Word Document
Configuring a Word Merge in SmartSimple is a three-step process: Create the MS Word document that wi ...
随机推荐
- ThinkPHP实现事务回滚示例代码(附加:PDO的事务处理)
ThinkPHP的事务回滚示例如下: $m=D('YourModel');//或者是M(); $m2=D('YouModel2'); $m->startTrans();//在第一个模型里启用就可 ...
- 解决tomcat启动慢
1.在Tomcat环境中解决 可以通过配置JRE使用非阻塞的Entropy Source. 在catalina.sh中加入这么一行:-Djava.security.egd=file:/dev/./ur ...
- 使用xftp连接VirtualBox中的centos6.5
首先要在windows上安装xftp软件,这个是傻瓜式操作就不说了 安装完毕之后,在centos上查看是否装了xftpd服务. [root@centos Desktop]# rpm -qa | gre ...
- 文本检测: CTPN
参考: https://zhuanlan.zhihu.com/p/37363942 https://zhuanlan.zhihu.com/p/34757009 https://zhuanlan.zhi ...
- springboot 异步任务
Spring Boot 揭秘与实战(七) 实用技术篇 - 异步任务拓展阅读: http://www.jianshu.com/p/86e915d616c4 发表于 2017-01-06 | Spring ...
- 跨服务器查询信息的sql
--跨服务器查询信息的sql: select * from openrowset( 'SQLOLEDB', '192.168.1.104'; 'sa'; '123.com',[AutoMonitorD ...
- centos7下忘记mysql5.7密码
才装完的mysql,转眼密码就忘记了,找了一圈的修改密码方法,做下记录! 编辑mysql配置文件. [root@localhost ~]# vi /etc/my.cnf 在[mysqld]配置节下新增 ...
- java 清除 bom
参考工具 http://akini.mbnet.fi/java/unicodereader/ Utf8BomRemover 清除bom的方法 package cn.com.do1.component ...
- eclipse配置xml的自动提示
如mybatis的mapper配置文件: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE ...
- HTTP Header Accept-Language的ctf
题目也不知道该怎么取,但是是实在的一个案例.分享给大家. 种族歧视分值: 300 小明同学今天访问了一个网站,竟然不允许中国人访问!太坑了,于是小明同学决心一定要进去一探究竟! 发现accept-L ...