Creating Word Documents

It’s very easy to create Word documents from XSLT. We saw the definitive “Hello, World” example for WordprocessingML in Chapter 2. Example 3-1 shows the “Hello, World” example for creating a Word document from XSLT.

Example 3-1. Creating a Word document from XSLT

<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml">
   
  <xsl:template match="/">
    <xsl:processing-instruction name="mso-application">
      <xsl:text>progid="Word.Document"</xsl:text>
    </xsl:processing-instruction>
    <w:wordDocument>
      <xsl:attribute name="xml:space">preserve</xsl:attribute>
      <w:body>
        <w:p>
          <w:r>
            <w:t>Hello, World!</w:t>
          </w:r>
        </w:p>
      </w:body>
    </w:wordDocument>
  </xsl:template>
   
</xsl:stylesheet>

As you can see, there’s little to it, beyond slapping xsl:stylesheet and xsl:template elements around the w:wordDocument element. The only additional provisions you need to make are for generating the mso-application PI and the xml:space="preserve" directive in the result. (Using the xsl:attribute element as opposed to a literal xml:space attribute ensures that whitespace will be preserved in the result but not in the stylesheet.)

Obviously, Example 3-1 isn’t terribly interesting in its own right. What is interesting is how you can extend it. With XSLT’s power and a basic knowledge of WordprocessingML at your disposal, you can create dynamic Word documents quite easily. We’ll take a look at one example of doing this: ...

Get Office 2003 XML now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.