Blogs

Blogs

Open XML Usage – Part One

9th October 2014

Part One

This will be the first in a short series of articles to show how we use Open XML.

Open XML is a Microsoft format which can be used to programmatically create Word documents.

Below is a code example and associated output.

I have not shown all the code examples yet  as these will be explained in future blogs.

The code shown constructs a page containing a header and footer, a document heading, some normal text a table and a watermark. Styling has been applied to all these elements.

I have created separate classes and methods to encapsulate the commonly used code, otherwise the code becomes inflated and unreadable.

//------------------------------------------------------------------------------------------------- 
// <copyright file="Default.aspx.cs" company="PSP">
//  Copyright (c) PSP. All rights reserved.
// </copyright>
//-------------------------------------------------------------------------------------------------
namespace ExportToWord
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.UI;
    using DocumentFormat.OpenXml;
    using DocumentFormat.OpenXml.Packaging;
    using DocumentFormat.OpenXml.Vml.Office;
    using DocumentFormat.OpenXml.Wordprocessing;

    public partial class _Default : System.Web.UI.Page
    {
        protected void ExportToWord_Click(object sender, EventArgs e)
        {
            string documentFilename = "OpenXML Export To Word Example.docx";

            using (MemoryStream documentStream = new MemoryStream())
            {
                //// Create a Wordprocessing document. 
                using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(documentStream, WordprocessingDocumentType.Document))
                {
                    //// Add a new main document part. 
                    MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();

                    ////Create DOM tree for a simple document. 
                    mainPart.Document = new Document();

                    mainPart.Document.Body = new Body();

                    //// Add a header part
                    HeaderPart headerPart = WordDocument.CreateHeaderPart(wordDoc);

                     ////Create the header content
                    CreateHeader(wordDoc, headerPart);

                    //// Add a text watermark
                    TextWatermark textWatermark = new TextWatermark();
                   textWatermark.AddWatermark(wordDoc, "DRAFT", "font-family:\"Calibri\";font-size:medium", "#C0C0C0");

                    //// Add a footer part
                    FooterPart footerPart = WordDocument.CreateFooterPart(wordDoc);

                    //// Create the footer content
                    string footerText = "Example footer text"; 
                    CreateFooter(mainPart, footerText, JustificationValues.Left, footerPart);

                    //// Get the Styles part for this document.
                    StyleDefinitionsPart part = mainPart.StyleDefinitionsPart;

                    //// If the Styles part does not exist, add it.
                    if (part == null)
                    {
                        part = WordDocument.AddStylesPartToPackage(wordDoc);
                    }

                    //// Create and add all the character styles
                    //// This will set the font, font size, color, bold and italics
                    WordDocument.CreateAndAddCharacterStyle(part, "Heading1", "Heading1", "Heading1", "Calibri", "56", string.Empty, true, false);
                    WordDocument.CreateAndAddCharacterStyle(part, "Normal", "Normal", "Normal", "Calibri", "22", string.Empty, false, false);
                    WordDocument.CreateAndAddCharacterStyle(part, "NormalBold", "Normal Bold", "Normal Bold", "Calibri", "22", string.Empty, true, false);
                    WordDocument.CreateAndAddCharacterStyle(part, "NormalGrey", "Normal Grey", "Normal Grey", "Calibri", "22", "808080", false, false);
                    WordDocument.CreateAndAddCharacterStyle(part, "NormalGreySmall", "Normal Grey Small", "Normal Grey Small", "Calibri", "18", "75A3A3", false, false);
                    WordDocument.CreateAndAddCharacterStyle(part, "TableCellHeaderStyle", "Table Cell Style", "Table Cell Style", "Calibri", "22", string.Empty, true, false);
                    WordDocument.CreateAndAddCharacterStyle(part, "TableCellStyle", "Table Cell Style", "Table Cell Style", "Calibri", "22", string.Empty, false, false);
                    
                    Body body = new Body();
                    Paragraph p = new Paragraph();

                    //// This creates a normal page margin of 2.54 cm (1440)
                    SectionProperties sectionProps = new SectionProperties();
                    PageMargin pageMargin = new PageMargin() { Top = 1440, Right = (UInt32Value)1440U, Bottom = 1440, Left = (UInt32Value)1440U };
                    sectionProps.Append(pageMargin);
                    body.Append(sectionProps);

                    //// Create the heading text
                    Run runHeading = new Run();
                    runHeading.RunProperties = new RunProperties() { RunStyle = new RunStyle() { Val = "Heading1" } };
                    runHeading.Append(new Text("OpenXML Example"));
                    p = new Paragraph(new Run(runHeading));
                    body.Append(p);

                    //// Create the normal text
                    Run runNormalText = new Run();
                    runNormalText.RunProperties = new RunProperties() { RunStyle = new RunStyle() { Val = "Normal" } };
                    runNormalText.Append(new Text("This is an example page for OpenXML usage."));
                    p = new Paragraph(new Run(runNormalText));
                    body.Append(p);

                    mainPart.Document.Append(body);

                    body = new Body();
                    CreateTable(body);

                    //// Add a break after the paragraph
                    p = new Paragraph(new Run(new Break()));
                    body.Append(p);
                    mainPart.Document.Append(body);

                    mainPart.Document.Save();
                    wordDoc.Close();

                    //// Send the document to the browser
                    WordDocument.RespondStreamToWord(documentStream, documentFilename);

                } //// End word doc
            } //// End Memory Stream              
        }
    }
}

This website uses cookies to provide the best possible experience. By continuing to use our website you are agreeing to our use of cookies.