Add style to Docx in Novacode

Sean picture Sean · Mar 27, 2015 · Viewed 8.9k times · Source

Using Novacode's DocX, I can add a paragraph with Heading 1 style like this:

var p = docX.InsertParagraph("My Heading");
p.StyleName = "Heading1";

But I can't add a "Title" style:

var p = docX.InsertParagraph("My Heading");
p.StyleName = "Title";

I looked in the generated Xml files, and I see the "Title" style is not in the Styles.xml file, whereas if I set it as Title style in Word and save, then the Title style appears in the styles Xml file.

So how do I either get DocX to include the Title style, or how do I go about adding a style to the DocX styles?

Answer

xwing picture xwing · Jul 2, 2016

I meet this problem too. By comparing word\document.xml and word\styles.xml files in the docx(zipped)file. I found that the Paragraph.StyleName should be assigned with the style id not the style name !

for example: one style in styles.xml:

<w:style w:type="paragraph" w:customStyle="1" w:styleId="a9">
    <w:name w:val="mystyle" /> 

You should assign "a9" not "mystyle" to Paragraph.StyleName to get the correct style.

Hope helpful.