Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
607 views
in Technique[技术] by (71.8m points)

ms word - How to programatically (C#) determine the pages count of .docx files

I have about 400 files in .docx format, and I need to determine the length of each in #pages.

So, I want to write C# code for selecting the folder that contains the documents , and then returns the #pages of each .docx file.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To illustrate how this can be done, I have just created a C# console application based on .NET 4.5 and some of the Microsoft Office 2013 COM objects.

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:UsersMyNameDocumentsword.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();
        }
    }
}

For this to work you need to reference the following COM objects:

  • Microsoft Office Object Library (version 15.0 in my case)
  • Microsoft Word Object Library (version 15.0 in my case)

The two COM objects gives you access to the namespaces needed.

For details on how to reference the correct assemblies, please refer to section: "3. Setting Up Work Environment:" at: http://www.c-sharpcorner.com/UploadFile/amrish_deep/WordAutomation05102007223934PM/WordAutomation.aspx

For a quick and more general introduction to Word automation through C#, see: http://www.dotnetperls.com/word

-- UPDATE

Documentation about the method Document.ComputeStatistics that gives you access to the page count can be found here: http://msdn.microsoft.com/en-us/library/microsoft.office.tools.word.document.computestatistics.aspx

As seen in the documentation, the method takes a WdStatistic enum that enables you to retrieve different kinds of stats, e.g., the total amount of pages. For an overview of the complete range of stats you have access to, please refer to the documentation of the WdStatistic enum, which can be found here: http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.wdstatistic.aspx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...