Matt Cashatt
Matt Cashatt

Reputation: 24218

How do I add structured content to a Word Document via Interop (C#)?

Thanks for looking. I am writing some C# to create a word doc based on a dataset. Using Microsoft.Office.Interop.Word I am able to create a document with formatted headings for the sections, but there is no associated structure. In other words, I can't see my sections in the Navigation pane or generate a Table of Contents.

Here is what I am trying:

Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document document = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);

document.Range(0, 0);

foreach (var solutionModel in solutions)
{
    var hText = document.Paragraphs.Add();
    hText.Format.SpaceAfter = 10f;
    hText.set_Style(Microsoft.Office.Interop.Word.WdBuiltinStyle.wdStyleHeading1);
    hText.Range.Text = solutionModel.Name;
    hText.Range.InsertParagraphAfter();

    var pText = document.Paragraphs.Add();
    pText.Format.SpaceAfter = 50f;
    pText.set_Style(Microsoft.Office.Interop.Word.WdBuiltinStyle.wdStyleNormal);
    pText.Range.Text = "Lorem ipsum dolor sit amet.";
    pText.Range.InsertParagraphAfter();
}

WordApp.Visible = true;

This renders nicely in Word with the headings (hText) taking on the native Header 1 style, but there is no associated structure.

Upvotes: 1

Views: 950

Answers (2)

Maarten van Stam
Maarten van Stam

Reputation: 1899

Initially I was thinking the same as @Dirk mentioned in the comments, but tested it and as you've seen yourself that didn't work in your code.

After doing some more research I found that my other answer actually did not result in having the right Header Style applied to your added paragraphs. So my testing resulted in the following outcome:

You need to set the text before applying the style.

var hText = document.Paragraphs.Add();

hText.Range.Text = solutionModel.Name; // <--

hText.set_Style(Microsoft.Office.Interop.Word.WdBuiltinStyle.wdStyleHeading1);
hText.Format.SpaceAfter = 10f;
hText.Range.InsertParagraphAfter();

I added two empty rows to bring attention to the position of the Text line location, but you can leave that out.

Upvotes: 2

Maarten van Stam
Maarten van Stam

Reputation: 1899

You can set the OutlineLevel (that is located on the ParagrapFormat of a Paragraph's Range) to the desired level (VBA):

ActiveDocument.Paragraphs(1).Range.ParagraphFormat.OutlineLevel = wdOutlineLevel1

In your case (C#):

hText.Range.Text = solutionModel.Name;
hText.Range.ParagraphFormat.OutlineLevel = Microsoft.Office.Interop.Word.WdOutlineLevel.wdOutlineLevel1;

This will add the selected paragraph to the Navigation View

Upvotes: 2

Related Questions