I am building a word document using Office's Word interop. I am settings heading styles via code. The content is getting styled correctly, however, one opening the created word document, the style is not selected for the selection in the header. This is causing the table of contents to not find the heading.
object oMissing = Missing.Value;
//Start Word and create a new document.
var application = new Application();
application.Visible = true;
var document = application.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
foreach (var member in assembly.Members)
{
//Insert a paragraph at the beginning of the document
var paragraph = document.Content.Paragraphs.Add(ref oMissing);
paragraph.set_Style(WdBuiltinStyle.wdStyleHeading1);
paragraph.Range.Text = member.MemberName;
paragraph.Range.InsertParagraphAfter();
}
document.TablesOfContents.Add(document.Content, true /*use heading styles*/, oMissing, oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing, oMissing,
oMissing, oMissing);
document.SaveAs(@"C:\test.docx", oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
document.Close();
application.Quit();
This example causes the table of contents to display "No entries found".
Note that the content is correctly styled with the heading style. However, when I open the document manually and select "Heading 1", then the table of contents finds the entry correctly.
Any ideas why this would happen? I am callign set_Style with a built in style name. Why does it apply the style but not actually get treated as the style (in this case, a heading)?
UPDATE
Adding the following code seems to make only the first heading recognized as a heading in Word.
foreach (var member in assembly.Members)
{
document.ActiveWindow.Selection.set_Style(WdBuiltinStyle.wdStyleHeading1);
//Insert a paragraph at the beginning of the document
var paragraph = document.Content.Paragraphs.Add(ref oMissing);
paragraph.set_Style(WdBuiltinStyle.wdStyleHeading1);
paragraph.Range.Text = member.MemberName;
paragraph.Range.InsertParagraphAfter();
}