Count the Number of Words in a Word Document Using Java

Andrew Wilson
1 min readApr 21, 2022

When you are typing, the Microsoft Word will automatically counts the number of words in the status bar. Beyond that, it also counts the number pages, paragraphs and characters with or without spaces. This article will introduce how to programmatically count the number of words and characters in a Word document using the Free Spire.Doc for Java library.

Import JAR Dependency

Method 1: Download the free library and unzip it. Then add the Spire.Doc.jar file to your Java application as dependency.
Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>5.2.0</version>
</dependency>
</dependencies>

Sample Code

import com.spire.doc.*;

public class countWordsNumber {
public static void main(String[] args) {
//Create a Document instance
Document document = new Document();

//Load a sample Word document
document.loadFromFile("Input 1.docx");

//Count the number of words
System.out.println("WordCount: " + document.getBuiltinDocumentProperties().getWordCount());

//Count the number of characters without spaces
System.out.println("CharCount: " + document.getBuiltinDocumentProperties().getCharCount());

//Count the number of characters with spaces
System.out.println("CharCountWithSpace: " + document.getBuiltinDocumentProperties().getCharCountWithSpace());
}
}

--

--

Andrew Wilson

Explore C#, Java and Python solutions for processing Word/Excel/PowerPoint/PDF files.