DEV Community 👩‍💻👨‍💻


Posted on

Java/ Count the Number of Words in a Word Document

Microsoft Word will automatically counts the number of words, pages, paragraphs and characters with or without spaces when you type. In this article, you will learn how to programmatically count the number of words or characters in an existing Word document using a Free Java API.

Import JAR Dependency of the Free API

Method 1: Download the free API (Free Spire.Doc for Java) and unzip it. Then add the Spire.Doc.jar file to your Java application as dependency.
Method 2: You can also add the jar dependency to maven project by adding the following configurations to the pom.xml.

Enter fullscreen mode Exit fullscreen mode

Sample Code

The detailed steps and complete sample code are as follows:
● Create a Document instance.
● Load a sample Word document using Document.loadFromFile() method.
● Count the number of words using Document.getBuiltinDocumentProperties().getWordCount() method.
● Count the number of characters without spaces using Document.getBuiltinDocumentProperties().getCharCount() method.
● Count the number of characters with spaces using Document.getBuiltinDocumentProperties().getCharCountWithSpace() method.

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());
Enter fullscreen mode Exit fullscreen mode

count words

Top comments (0)

Want to help the DEV Community feel more like a community? 🥹

Head over to the Welcome Thread and greet some new community members!