News Category

Count the number of words in a document in C#, VB.NET

2014-10-13 07:20:07 Written by  support iceblue
Rate this item
(0 votes)

When you type in a document, Word automatically counts the number of pages and words in your document and displays them on the status bar – Word Count, at the bottom of the workspace. But how can we get the number of words, characters in an existing Word document through programming? This article aims to give you a simple solution offered by Spire.Doc.

Test file:

Count the number of words in a document in C#, VB.NET

Detailed Steps for Getting the Number of Words and Characters

Step 1: Create a new instance of Spire.Doc.Document class and load the test file.

Document doc = new Document();
doc.LoadFromFile("test.docx", FileFormat.Docx2010);

Step 2: Display the number of words, characters including or excluding spaces on console.

Console.WriteLine("CharCount: " + doc.BuiltinDocumentProperties.CharCount);
Console.WriteLine("CharCountWithSpace: " + doc.BuiltinDocumentProperties.CharCountWithSpace);
Console.WriteLine("WordCount: " + doc.BuiltinDocumentProperties.WordCount);

Output:

Count the number of words in a document in C#, VB.NET

Full Code:

[C#]
using Spire.Doc;
using System;
namespace CountNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("test.docx", FileFormat.Docx2010);
            Console.WriteLine("CharCount: " + doc.BuiltinDocumentProperties.CharCount);
            Console.WriteLine("CharCountWithSpace: " + doc.BuiltinDocumentProperties.CharCountWithSpace);
            Console.WriteLine("WordCount: " + doc.BuiltinDocumentProperties.WordCount);
            Console.ReadKey();
        }
    }
}
[VB.NET]
Imports Spire.Doc
Namespace CountNumber
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New Document()
			doc.LoadFromFile("test.docx", FileFormat.Docx2010)
			Console.WriteLine("CharCount: " + doc.BuiltinDocumentProperties.CharCount)
			Console.WriteLine("CharCountWithSpace: " + doc.BuiltinDocumentProperties.CharCountWithSpace)
			Console.WriteLine("WordCount: " + doc.BuiltinDocumentProperties.WordCount)
			Console.ReadKey()
		End Sub
	End Class
End Namespace

Additional Info

  • tutorial_title: Count the number of words
Last modified on Friday, 03 September 2021 03:24