Thursday, December 4, 2008

C#: Calculate Statistics of a Word Document

//***
//Label names are self Explanatory
//Stats include content from FootNotes and EndNotes
//Use objFalse = false instead of objMissing to exclude FootNotes and EndNotes
//***

Word.Document WDocument = Globals.ThisAddIn.Application.ActiveDocument;
object objMissing = System.Reflection.Missing.Value;

lblNumberOfPages.Text = WDocument.ComputeStatistics(Word.WdStatistic.wdStatisticPages, ref objMissing).ToString();

lblNumberOfParagraphs.Text = WDocument.ComputeStatistics(Word.WdStatistic.wd
StatisticParagraphs, ref objMissing).ToString();

lblNumberOfSentences.Text = WDocument.Sentences.Count.ToString();

lblNumberOfLines.Text = WDocument.ComputeStatistics(Word.WdStatistic.wdStatisticLines, ref objMissing).ToString();

lblNumberOfWords.Text = WDocument.ComputeStatistics(Word.WdStatistic.wdStatisticWords, ref objMissing).ToString();

lblNumberOfCharactersIncludingSpaces.Text = WDocument.ComputeStatistics(Word.WdStatistic.wdStatisticCharactersWithSpaces, ref objMissing).ToString();

lblNumberOfCharactersExcludingSpaces.Text = WDocument.ComputeStatistics(Word.WdStatistic.wdStatisticCharacters, ref objMissing).ToString();

4 comments:

  1. Extending this further, would that be possible to count:
    1. how many styles used in the particular documents then diplay what are the styles name?
    2. how many images in the document?

    Any idea?
    Thank you :)

    ReplyDelete
  2. which namespace I have to import for this one to work? Thanks in adance.

    ReplyDelete
  3. tatayya,
    You need the minimum of the following imports:

    using Word = Microsoft.Office.Interop.Word;
    using Office = Microsoft.Office.Core;

    ReplyDelete
  4. I have a lot of word documents on my PC. And one day something happened with theirs. I used the Google and noticed there a tool, which aided me quite simply and maybe can help in your condition - word repair.

    ReplyDelete

Please use your common sense before making a comment, and I truly appreciate your constructive criticisms.