2012-09-09 46 views

回答

15

为了说明如何做到这一点,我刚刚创建了一个基于.NET 4.5和一些Microsoft Office 2013 COM对象的C#控制台应用程序。

using System; 
using Microsoft.Office.Interop.Word; 

namespace WordDocStats 
{ 
    class Program 
    { 
     // Based on: http://www.dotnetperls.com/word 
     static void Main(string[] args) 
     { 
      // Open a doc file. 
      var application = new Application(); 
      var document = application.Documents.Open(@"C:\Users\MyName\Documents\word.docx"); 

      // Get the page count. 
      var numberOfPages = document.ComputeStatistics(WdStatistic.wdStatisticPages, false); 

      // Print out the result. 
      Console.WriteLine(String.Format("Total number of pages in document: {0}", numberOfPages)); 

      // Close word. 
      application.Quit(); 
     } 
    } 
} 

对于这个工作,你需要引用下面的COM对象:(在我的案件15.0版)

  • 微软Office对象库
  • Microsoft Word对象库(15.0版,在我的情况)

这两个COM对象使您可以访问所需的命名空间。

有关如何引用正确的组件,请参阅节的细节:“3.设置工作环境:”在:http://www.c-sharpcorner.com/UploadFile/amrish_deep/WordAutomation05102007223934PM/WordAutomation.aspx

对于通过C#快速,更全面的介绍到Word自动化,请参阅: http://www.dotnetperls.com/word

- UPDATE

有关该方法的Document.ComputeStatistics文档,让您访问的页面数量可以在这里找到:http://msdn.microsoft.com/en-us/library/microsoft.office.tools.word.document.computestatistics.aspx

如文档中所示,该方法采用WdStatistic枚举,该枚举使您可以检索不同类型的统计信息,例如总页数。对于您可以访问,请参阅WdStatistic枚举的文档,可以在这里找到统计数据的完整系列的概述:http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.wdstatistic.aspx

3

使用DocumentFormat.OpenXml.dll你可以在C找到DLL:\ PROGRAM文件\打开XML SDK \ V2.0 \ lib中

示例代码:

DocumentFormat.OpenXml.Packaging.WordprocessingDocument doc = DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Open(docxPath, false); 
      MessageBox.Show(doc.ExtendedFilePropertiesPart.Properties.Pages.InnerText.ToString()); 

使用DocumentFormat.OpenXml.Packaging.WordprocessingDocument类,你需要在你的项目

文件添加下列引用umentFormat.OpenXml.dll & WindowsBase.dll中

+0

我已经写了下面的代码来执行在Windows应用程序的任务,但我有错误: – AyaZoghby

+0

@AyaZoghby你能不能给我错误的详细信息?因为在我的电脑它工作正常。 –

+0

它适用于.doc文件?或只是.docx(基于openxml)? –

相关问题