将“范围”设置为从文档的第二页开始

本文关键字:开始 二页 文档 范围 设置 | 更新日期: 2023-09-27 18:24:24

我需要更改目录的范围,以便从word文档的第二页开始。有人可以帮我设置范围吗?

下面的代码是我目前拥有的范围,但这将在单词文档的开头生成目录,我需要将其插入第二页。

object start = oWord.ActiveDocument.Content.Start;
Word.Range rangeForTOC = oDoc.Range(ref oMissing, ref start);

这就是我正在测试的:

object gotoPage1 = Word.WdGoToItem.wdGoToPage;
object gotoNext1 = Word.WdGoToDirection.wdGoToAbsolute;
object gotoCount1 = null;
object gotoName1 = 1;
oWord.Selection.GoTo(ref gotoPage1, ref gotoNext1, ref gotoCount1, ref gotoName1);
//Insert a blank page  
oWord.Selection.InsertNewPage();
oWord.Selection.InsertNewPage();
object what = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToPage;
object which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToAbsolute;
object count = 2; //change this number to specify the start of a different page
oWord.Selection.GoTo(ref what, ref which, ref count, ref oMissing);

Object beginPageTwo = oWord.Selection.Range.Start;
// This gets the start of the page specified by count object
Word.Range rangeForTOC = oDoc.Range(ref oMissing, ref beginPageTwo);
object oTrueValue = true;

将“范围”设置为从文档的第二页开始

以下是您应该如何做到这一点:

object missing = System.Reflection.Missing.Value;
object what = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToPage;
object which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToAbsolute;
object count = 2; //change this number to specify the start of a different page
oWord.Selection.GoTo(ref what, ref which, ref count, ref missing);
Object beginPageTwo = oWord.Selection.Range.Start; // This gets the start of the page specified by count object
Word.Range rangeForTOC = oDoc.Range(ref beginPageTwo); //modified this line per comments

上面的代码包含了SO的代码——我们如何在c sharp中打开一个具有特定页码的word文件?

用于验证这一点的测试代码基于注释:(已编辑)

object fileName = (object)@"C:'test.docx";
object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Application oWord = new Application();
oWord.Documents.Open(ref fileName);
object gotoPage1 = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToPage;
object gotoNext1 = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToAbsolute;
object gotoCount1 = null;
object gotoName1 = 1;
oWord.Selection.GoTo(ref gotoPage1, ref gotoNext1, ref gotoCount1, ref gotoName1);
//Insert a blank page  
oWord.Selection.InsertNewPage();
object what = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToPage;
object which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToAbsolute;
object count = 2; //change this number to specify the start of a different page
oWord.Selection.GoTo(ref what, ref which, ref count, ref oMissing);
Object beginPageTwo = oWord.Selection.Range.Start; // This gets the start of the page specified by count object
Microsoft.Office.Interop.Word.Range rangeForTOC = oWord.ActiveDocument.Range(ref beginPageTwo);
oWord.ActiveDocument.TablesOfContents.Add(rangeForTOC);

我使用Visual Studio 2012 Premium针对.NET Framework 4.0针对Word 2010测试了此代码。