Search code examples
c#ms-wordoffice-interop

Generate multilevel list in Word from C#


I have Microsoft Word docx document in which is some text and placeholders. This file is template that is populated with data from C# application. I have problem with one thing - multilevel lists.

In docx I have this:

  • {placeholder}

And in C# I am using this code:

Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
...
object ph = "{placeholder}";
string replaceWith = "item1" + "\n" + "item2";
wordApp.Selection.Find.Execute(ref ph);
wordApp.Selection.Text = replaceWith;

It generate what is expected:

  • item1
  • item2

But I would like to use something like this:

...
string replaceWith = "item1" + "\n\t" + "item2";
...
wordApp.Selection.Text = replaceWith;

To generate this (idealy with bullet style like is in MS Word (second level is empty bullet)):

  • item1
    • item2

But the output (wrong) is:

  • item1
  •     item2

Solution

  • It's not possible to include this kind of paragraph formatting in a string. Yes, the Word application can be set up to behave as you describe for the end-user, when TAB is pressed. But this does not carry over to the programming APIs. The code needs to apply the outline level on the second paragraph after the string has been inserted. Something like:

    Selection.Paragraphs[2].OutlineDemote