65.9K
CodeProject 正在变化。 阅读更多。
Home

计算 MS Word 文档的页数

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.44/5 (19投票s)

2003 年 4 月 30 日

viewsIcon

175742

downloadIcon

1

使用 C# 访问 Word 文档属性的简单方法。

引言

本文档介绍了如何使用 C# 以编程方式统计 MS Word 文档中的页数。

使用代码

要统计 MSWord 文档中的页数,我们需要按照以下步骤操作:

  1. 创建 Word 应用程序对象。
  2. 使用 Word 文档的 Documents 集合的 open() 函数打开所需的 Word 文档。 此函数返回 Word.Document 对象。
  3. 在 Word.Document 对象上调用 ComputeStatistics 函数,并传递一个枚举 WdStatistic,其值等于 wdStatisticPages。 此函数将返回打开的 Word 文档中的页数。

以下是代码:

using System; 

namespace DocPageCounter 
{ 
      class PageCounter 
      { 
            /// <SUMMARY> 
            /// The main entry point for the application. 
            /// </SUMMARY> 
            [STAThread] 
            static void Main(string[] args) 
            { 
                Word.ApplicationClass WordApp = new Word.ApplicationClass(); 

                // give any file name of your choice. 
                object fileName = "D:\\abc\\oop1.doc"; 
                object readOnly = false; 
                object isVisible = true;

                //  the way to handle parameters you don't care about in .NET 
                object missing = System.Reflection.Missing.Value; 

                //   Make word visible, so you can see what's happening 
                //WordApp.Visible = true; 
                //   Open the document that was chosen by the dialog 
                Word.Document aDoc = WordApp.Documents.Open(ref fileName, 
                                        ref missing,ref readOnly, ref missing,
                                        ref missing, ref missing, ref missing,
                                        ref missing, ref missing, ref missing,
                                         ref missing, ref isVisible);

                Word.WdStatistic stat = Word.WdStatistic.wdStatisticPages ; 
                int num =  aDoc.ComputeStatistics(stat,ref missing); 
                System.Console.WriteLine ("The number of pages in doc is {0}", 
                                          num); 
                System.Console.ReadLine(); 
            } 
      } 
} 
© . All rights reserved.