计算 MS Word 文档的页数






3.44/5 (19投票s)
2003 年 4 月 30 日

175742

1
使用 C# 访问 Word 文档属性的简单方法。
引言
本文档介绍了如何使用 C# 以编程方式统计 MS Word 文档中的页数。
使用代码
要统计 MSWord 文档中的页数,我们需要按照以下步骤操作:
- 创建 Word 应用程序对象。
- 使用 Word 文档的 Documents 集合的 open() 函数打开所需的 Word 文档。 此函数返回 Word.Document 对象。
- 在 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();
}
}
}