Adding HTML to Word using OpenXML but unable to style the content (.Net Core)


I managed to add HTML (text only) to a Word-document following this post Add HTML String to OpenXML, using an already existing Word-file.

Unfortunately, I can’t find any solution to use style from this Word-template for my newly added text. It is always “Times New Roman” size 12px although the standard style of the used template is “Arial” size 9px.

So fare I tried:

  1. Using the ParagraphProperties as I would do for not HTML texts.
 Paragraph para = body.AppendChild(new Paragraph());
 Run run = para.AppendChild(new Run());
 para.ParagraphProperties = new ParagraphProperties(new ParagraphStyleId() { Val = "berschrift2" });
  1. Turnig MatchSource off
 AltChunkProperties altChunkProperties = new AltChunkProperties();
 altChunkProperties.MatchSource = new MatchSource() { Val = new OnOffValue(false) };

Any suggestions?

I found a workaround, which isnĀ“t really a solution for my question, but works for me. I’m no longer trying to use the style from word, but adding the styles to my html before using altchunk.


The real solution for your question is to transform HTML into Open XML markup “yourself” rather than relying on the alternative format import parts in conjunction with w:altChunk elements. This creates a dependency on how Microsoft Word handles the import, often with little control on your side.

How do you transform HTML (or XML in general) to Open XML markup? The best way is to write so-called recursive pure functional transformations, which translate HTML elements and attributes to Open XML elements and attributes. If you have really simple HTML documents, that is not a big task. However, doing this for “arbitrary” HTML and CSS is quite a feat.

The good news is that the Open-XML-PowerTools, an Open Source library, contain functionality to transform HTML to Open XML and vice versa. Thus, I’d recommend you have a look at that library.

Answered By – Thomas Barnekow

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.