How to apply a Word Quick Style in C# - not just simple formatting but the entire style?

13,893

This works for me.

Word.Application _wordApp = new Word.Application();
Word.Document oDoc = _wordApp.Documents.Add();
_wordApp.Visible = true;
_wordApp.Selection.TypeText("Heading");
oDoc.Paragraphs[1].set_Style(Word.WdBuiltinStyle.wdStyleHeading2);

When you say

paragraph.Range.Text = text + paragraph.Range.Text;

You are getting more paragraphs than you imagined. I reckon you need:

paragraph.Range.Text = text;

Try:

Paragraph paragraph = _document.Content.Paragraphs.Add();
paragraph.Range.Text = text;

if (styleName != null)
{ 
    paragraph.set_Style(_document.Styles[styleName]);
}

paragraph.Range.InsertParagraphAfter();
Share:
13,893
Johny Skovdal
Author by

Johny Skovdal

Updated on June 09, 2022

Comments

  • Johny Skovdal
    Johny Skovdal almost 2 years

    I admit, I am very new to using the Interop libraries, but the advice people always seem to give is, record a macro and check out the vba code. The problem is, the macro does not record exactly what I am doing: Clicking a Quick Style to apply it to the current selection.

    My task is pretty simple: I need to apply a Quick Style to a Paragraph (Microsoft.Office.Interop.Word.Paragraph). Using the set_style command however, only applies basic formatting, and the paragraph keeps it original Quick Style selection (Normal).

    Using Remou's approach it worked for me though, but it seems very similar to my own code, and I can not make it work, and I think it might be my understanding of the objectmodel that is a bit off.

    public void AddParagraph(string text, string styleName = null)
    {
      Paragraph paragraph = _document.Content.Paragraphs.Add();
      if (styleName != null)
      {
        paragraph.Range.set_Style(_document.Styles[styleName]);
      }
    
      paragraph.Range.Text = text;
      paragraph.Range.InsertParagraphAfter();
    }
    

    I then call it with e.g. AddParagraph("A title", "Heading 1");, but the result of using the above wrapper to build my document is, that no complete styles are applied, only font, color, size and bold/italics.

    I am using my own .dotx file, with my own defined and named styles, but simply copying the code from Remou works with my own template, so I do not think that is the issue, and using that code I am unable to figure out how to append multiple paragraphs with each their own styling.

    Can anyone point out what is wrong with my approach, or at least how I can make the answer provided by Remou work for my requirements? :)