Note: Cross posted from Coding The Document.
Permalink
 

In the templates that I have processed with Open XML there are usually a number of tables.  Some times we have to add an extra paragraph to a cell and we want to keep the formatting of the text already in the cell.  In this post I will go over how to apply bold and underline formatting to text as well as how to steal it from existing text and apply it to a new paragraph or run.

In order to apply an underline format to a paragraph by hand you have to start with the ParagraphProperties.  To that you append a ParagraphMarkRunProperties object to which you have appended an Underline object.  It isn’t that complicated.  There are just a lot of objects that have to be instantiated to format a paragraph.  Below is an example of what I have just described.

Paragraph newParagraph = new Paragraph();
ParagraphProperties newProperties = new ParagraphProperties();
 
ParagraphMarkRunProperties markRunProperties = new ParagraphMarkRunProperties();
Underline newUnderline = new Underline { Val = UnderlineValues.Single };
markRunProperties.AppendChild(newUnderline);
newProperties.AppendChild(markRunProperties);
 
newParagraph.AppendChild(newProperties);
wordprocessing.Run newRun = new wordprocessing.Run();
wordprocessing.Text newText = new wordprocessing.Text("Text for the new paragraph");
newRun.AppendChild(newText);

In order to make a paragraph or run bold you append a Bold object instead of or as well as the Underline object.

If you have an existing paragraph that you can steal from the code gets a lot easier.  The code below does just that by cloning the ParagraphProperties from the existing paragraph and appending it to the new paragraph.

ParagraphProperties properties = (ParagraphProperties)oldParagraph.ParagraphProperties.Clone();
newParagraph.AppendChild(props);

Of course which approach you take will depend on what you situation is.  If you are allowing a user to define formatting through an interface other than a template you will have to use the first example.  This is one more reason to use a base file as a template.  Either way you should be able to accomplish the goal of formatting your text.