使用VSTO和Word创建目录

时间:2014-09-22 23:00:51

标签: c# ms-word vsto

下面的代码应该创建一个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();

1 个答案:

答案 0 :(得分:0)

此代码适用于我,请尝试:

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);