使用VSTO和Word创建目录

本文关键字:创建目录 Word VSTO 使用 | 更新日期: 2023-09-27 18:24:09

下面的代码应该创建一个word文档,然后生成一个目录。它应该只有一个名为"INTRODUCTION"的项,但我一直收到一个错误,说"发生了"system.runtime.interopservicesCOMException"类型的未处理异常。

object oMissing = System.Reflection.Missing.Value;
object oEndOfDoc = "''endofdoc"; /* 'endofdoc is a predefined bookmark */
//Start Word and create a new document.
Word.Application oWord = new Word.Application();
Word.Document oDoc = new Word.Document();
oWord.Visible = true;
oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
object oTrue = true;
object oFalce = false;
object styleHeading2 = "Heading 2";
object styleHeading3 = "Heading 3";
oWord.Selection.Range.set_Style(ref styleHeading2);
oWord.Selection.Range.set_Style(ref styleHeading3);
oWord.Selection.Paragraphs.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevel2;
oWord.Selection.Paragraphs.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevel3;
oWord.Selection.Paragraphs.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevelBodyText;
object oBookMarkTOC = "Bookmark_TOC";
Word.Range rngTOC = oDoc.Bookmarks.get_Item(ref oBookMarkTOC).Range;  <=== Error Occurs On This Line
rngTOC.Select();
object oUpperHeadingLevel = "1";
object oLowerHeadingLevel = "3";
object oTOCTableID = "TableOfContents";
oDoc.TablesOfContents.Add(rngTOC, ref oTrue, ref oUpperHeadingLevel, ref oLowerHeadingLevel, ref oMissing, ref oTOCTableID, ref oTrue, ref oTrue, ref oMissing, ref oTrue, ref oTrue, ref oTrue);
Word.Paragraph oIntro;
oIntro = oDoc.Content.Paragraphs.Add(ref oMissing);
oIntro.Range.Text = "INTRODUCTION";
oIntro.Range.set_Style(ref styleHeading2);
oIntro.Range.Font.Bold = 1;
oIntro.Range.Font.Name = "Arial";
oIntro.Range.Font.Size = 12;
oIntro.Format.SpaceAfter = 15;    
oIntro.Range.InsertParagraphAfter();

Word.Paragraph oPara1;
oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
oPara1.Range.Text = "This is the paragraph after the Introduction Title.";
oPara1.Range.set_Style(ref styleHeading2);
oPara1.Range.Font.Bold = 0;
oPara1.Range.Font.Name = "Arial";
oPara1.Range.Font.Size = 12;
oPara1.Format.SpaceAfter = 15;    
oPara1.Range.InsertParagraphAfter();
//Update table of contents
oDoc.TablesOfContents[1].Update();

使用VSTO和Word创建目录

这段代码对我有效,试试看:

selection.Font.Bold = 1;
selection.TypeText("Table of Content'n");  
TableOfContents toc = wordDoc.TablesOfContents.Add(selection.Range, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);