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:
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:
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