我有大约400个.docx格式的文件,我需要确定#pages中每个文件的长度。如何以编程方式(C#)确定.docx文件的页数
所以,我想编写C#代码来选择包含文档的文件夹,然后返回每个.docx文件的#页。
我有大约400个.docx格式的文件,我需要确定#pages中每个文件的长度。如何以编程方式(C#)确定.docx文件的页数
所以,我想编写C#代码来选择包含文档的文件夹,然后返回每个.docx文件的#页。
为了说明如何做到这一点,我刚刚创建了一个基于.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版)
这两个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
使用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中
我已经写了下面的代码来执行在Windows应用程序的任务,但我有错误: – AyaZoghby
@AyaZoghby你能不能给我错误的详细信息?因为在我的电脑它工作正常。 –
它适用于.doc文件?或只是.docx(基于openxml)? –