我正在使用Office的Word interop創建Word文檔。我是通過代碼設置標題樣式。內容的樣式是正確的,但是,一個打開創建的文檔文檔,樣式未被選中用於標題中的選擇。這導致目錄沒有找到標題。在目錄中沒有顯示Office Word intertop標題樣式
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。爲什麼它應用了風格,但實際上並沒有將風格視爲風格(在這種情況下是標題)?
UPDATE
添加以下代碼似乎僅使第一個標題公認的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();
}