Fraser Connor Fraser Connor - 7 months ago 39
C# Question

Bullet points in Word with c# Interop

I have the following code which is supposed to add a bulleted list to a word document that I'm generating automatically. From other answers I believe the code is correct, but the result doesn't produce any bullet points at all, it doesn't seem to apply the indent either.
Any Ideas?

Microsoft.Office.Interop.Word.Paragraph assets;
assets = doc.Content.Paragraphs.Add(Type.Missing);

// Some code to generate the text

foreach (String asset in assetsList)
{
assetText = assetText + asset + "\n";
}

assets.Range.ListFormat.ApplyBulletDefault(Type.Missing);

// Add it to the document
assets.Range.ParagraphFormat.LeftIndent = -1;
assets.Range.Text = assetText;
assets.Range.InsertParagraphAfter();

Answer Source

This happens because you're adding multiple paragraphs to the range after the range (it seems that setting the Text property is equivalent to InsertAfter). You want to InsertBefore the range so that the formatting you set gets applied.

    Paragraph assets = doc.Content.Paragraphs.Add();

    assets.Range.ListFormat.ApplyBulletDefault();
    string[] bulletItems = new string[] { "One", "Two", "Three" };

    for (int i = 0; i < bulletItems.Length; i++)
    {
        string bulletItem = bulletItems[i];
        if (i < bulletItems.Length - 1)
            bulletItem = bulletItem + "\n";
        assets.Range.InsertBefore(bulletItem);
    }

Notice that we add an End of Paragraph mark to all items except the last one. You will get an empty bullet if you add one to the last.