- using Word = Microsoft.Office.Interop.Word;
-
- namespace VstoWordExample
- {
- class Program
- {
- static void Main(string[] args)
- {
- // 请确保你的项目引用了 Microsoft.Office.Interop.Word
-
- // 创建 Word 应用程序对象
- Word.Application wordApp = new Word.Application();
-
- // 打开文档
- Word.Document doc = wordApp.Documents.Open(@"C:\Path\To\Your\Document.docx");
-
- // 获取目录的范围
- Word.Range tocRange = GetTableOfContentsRange(doc);
-
- // 获取目录的起始页和结束页
- int startPage = GetPageNumber(doc, tocRange.Start);
- int endPage = GetPageNumber(doc, tocRange.End);
-
- // 输出结果
- Console.WriteLine($"Table of Contents starts on page {startPage} and ends on page {endPage}");
-
- // 关闭 Word 应用程序
- wordApp.Quit();
- }
-
- // 获取文档的页数
- static int GetPageNumber(Word.Document doc, int charPosition)
- {
- return doc.Range(1, charPosition).Information[Word.WdInformation.wdActiveEndPageNumber];
- }
-
- // 获取目录的范围
- static Word.Range GetTableOfContentsRange(Word.Document doc)
- {
- foreach (Word.TableOfContents toc in doc.TablesOfContents)
- {
- // 假设目录在文档的第一个表格中
- if (toc.Range.Tables.Count > 0)
- {
- return toc.Range;
- }
- }
-
- // 如果找不到目录,返回 null 或者处理其他逻辑
- return null;
- }
- }
- }
在 VSTO(Visual Studio Tools for Office)中,你可以使用 C# 或 VB.NET 与 Word 进行交互以获取文档的目录(Table of Contents)的起始页和结束页。以下是一个示例代码,演示如何获取目录的起始页和结束页:
上述代码假设目录是文档的第一个表格。你可以根据你的文档结构进行相应的修改。请注意,文档页数的计算可能受到页眉、页脚等因素的影响,具体实现可能需要更详细的处理逻辑。