Click here to Skip to main content
13,292,205 members (54,487 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


8 bookmarked
Posted 19 Feb 2013

OpenXML: How do I?

, 19 Feb 2013
Rate this:
Please Sign up or sign in to vote.
Struggling to get going with OpenXML here are some basics to give you that boost.....


OpenXML is the de facto means for working with Office Documents, and it provides a real power-house of functionality. But getting going is often difficult as there are hurdles like terminology, trying to understand the nature of the beast, and just finding some basic tutorials that are less technical and more practical. This is the very reason for this tip/tutorial. The focus here will be on WordProcessingML. 


Before we begin dipping our feet into the code, I'm making alot of assumptions, and the first that you have actually started the road of learning OpenXML but struggling a bit. If you are a complete newbie and not even sure what OpenXML is, here is some good grounding (my hot list): 

  1. Beginning Tutorials - A Must  
  2. An Overview of The Package Convention 
  3. OpenXML Wiki (reference by Keyword)
  4. OpenXML Introduction Wiki  
  5. Eric Whites Intro - A Must Must 
That should be sufficient to really get the ball rolling, and if you looking for a shortcut, Eric White's Intro is fantastic! 

Using the code 

Create a Document 

So our first task will be to create a document we can use. 

public static void HelloWorld(string docName)
    // Create a Wordprocessing document. 
    using (WordprocessingDocument package = 
      WordprocessingDocument.Create(docName, WordprocessingDocumentType.Document))
        // Add a new main document part. 
        // Create the Document DOM. 
        package.MainDocumentPart.Document =
          new Document(
            new Body(
              new Paragraph(
                new Run(
                  new Text("Hello World!")))));
        // Save changes to the main document part. 

The code is pretty simple - and adds a MainDocumentPart and adds the key structure necessary for a document.

Use a Template 

Next let's use a Template (*.dotx) as base for creating other Word documents (*.docx). One of the ways you can really short-cut your development time is to build a skeleton with all your formatting requirements and even static text, tables or media that will be necessary for the reports or documents you are creating, and using bookmarks only add in what is dynamic in nature. More about that to come. 

public static void CopyTemplate(string FileToMake)
    File.Copy(@"c:\temp\SERE_Template.dotx", FileToMake);
    using (WordprocessingDocument document = WordprocessingDocument.Open(FileToMake, true))
        // Get the Styles part for this document
        StyleDefinitionsPart part = document.MainDocumentPart.StyleDefinitionsPart;
        // Manipulate Document and It's Style

Change Style of Existing Document

One of the things many struggle with at the start is how to change the defaults for a document, so it mirrored across all the objects of a document. So instead of having to define a style for every paragraph, why not just define it once. For more information check this post on StackOverflow

public static void GetSetStyleFromDoc(string file)
    using (var document = WordprocessingDocument.Open(file,true))
        // Get the Styles part for this document
        StyleDefinitionsPart part = document.MainDocumentPart.StyleDefinitionsPart;
        foreach (Style style in part.RootElement.Elements<Style>())
            if (style.StyleId.Value.Equals("PartA", StringComparison.InvariantCultureIgnoreCase))
                style.StyleParagraphProperties.SpacingBetweenLines.Line = "276";
                style.StyleRunProperties.FontSize.Val = "14";
                style.StyleRunProperties.Color.Val = "4F81BD"; // font color
                ParagraphBorders paragraphBorders1 = new ParagraphBorders();
                TopBorder topBorder1 = new TopBorder(){ Val = BorderValues.Single, 
                  Color = "856363", Size = (UInt32Value)24U, Space = (UInt32Value)0U };
                LeftBorder leftBorder1 = new LeftBorder(){ Val = BorderValues.Single, 
                  Color = "856363", Size = (UInt32Value)24U, Space = (UInt32Value)0U };
                BottomBorder bottomBorder1 = new BottomBorder(){ Val = BorderValues.Single, 
                  Color = "856363", Size = (UInt32Value)24U, Space = (UInt32Value)0U };
                RightBorder rightBorder1 = new RightBorder(){ Val = BorderValues.Single, 
                  Color = "856363", Size = (UInt32Value)24U, Space = (UInt32Value)0U };
                style.StyleParagraphProperties.ParagraphBorders = paragraphBorders1;

Add Text to a BookMark 

This feeds back to saving development time, instead of manually creating a document from scratch, rather take a template, set BookMarks in place, and then programmatically add the Document structures you need. This is tremendously effective.

public static void AddTextToBookmark(string fileName, string textToAdd)
    IDictionary<String, BookmarkStart> bookmarkMap = new Dictionary<String, BookmarkStart>();
    using (var document = WordprocessingDocument.Open(fileName, true))
        var doc = document.MainDocumentPart;
        foreach (BookmarkStart bookmarkStart in doc.RootElement.Descendants<BookmarkStart>())
            bookmarkMap[bookmarkStart.Name] = bookmarkStart;
        foreach (BookmarkStart bookmarkStart in bookmarkMap.Values)
            if (bookmarkStart.Name == "bkImage")
                Text text = new Text(textToAdd);
                Run run = new Run(new RunProperties(new Bold()));

I've attached a project with all the Source Code which also covers (which you can download from above) 

  1. Adding a Table 
  2. Adding an Image   
  3. Adding Text To A Page that is Landscape Mode 

Points of Interest 

Again this is not a HOWTO or a beginner tutorial but some real hard practical code to get you started on your own project. Further in the Project Solution I have attached there should be sufficient building blocks for any project.  


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Dane Balia
Software Developer (Senior) Senwes
South Africa South Africa
Hacking at code.....

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
Jim Meadors25-Feb-13 20:56
memberJim Meadors25-Feb-13 20:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171207.1 | Last Updated 19 Feb 2013
Article Copyright 2013 by Dane Balia
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid