我正在使用 Office 的 Word 互操作构建一个 Word 文档。我正在通过代码设置标题样式。内容的样式正确,但是,打开创建的 word 文档时,没有为标题中的选择选择样式。这导致目录找不到标题。
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();
此示例导致目录显示“未找到条目”。
请注意,内容的样式与标题样式正确。但是,当我手动打开文档并选择“标题 1”时,目录会正确找到条目。
任何想法为什么会发生这种情况?我是带有内置样式名称的 callign set_Style。为什么它应用样式但实际上并未被视为样式(在本例中为标题)?
更新
添加以下代码似乎只使第一个标题被识别为 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();
}