How to Create a Word Document with JAVA [2021 Update]

How to generate MS word documents automatically? I started to search how to accomplish this task and found the Apache POI library. We can easily work with MS Office documents (word, excel, etc.) with the Apache POI library. For details please visit https://poi.apache.org.

I want to continue with my case. I needed to get values (parameters) from a text file or excel file and generate multiple word documents according to those values. For simplicity, I selected to use a text file for reading parameters and then generate word documents. Lets’ get started!

I divided my code into three parts.

1) ReadFile Class: Reads the text file and returns a list of values. These values will be our parameters for word generation.

2) WordGenerator Class: It contains getLines and createWord methods. First, we get the values with getLines method and createWord method to create word documents.

3) Main Class: This is our top-level class in which we instantiate WordGenerator Class and call its methods.

ReadFile Class

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class ReadFile {
    public List<String> readLines(File filename) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));
        List<String> lines = bufferedReader.lines()
            .filter(Objects::nonNull)
            .collect(Collectors.toList());
        bufferedReader.close();
        return lines;
    }
}

WordGenerator Class

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class WordGenerator {
    public List<String> getLines(File fileName) throws Exception {
        ReadFile rf = new ReadFile();
        List<String> lines = rf.readLines(fileName);
        lines.forEach(System.out::println);
        return lines;
    }

    //Create Word
    public void createWord(List<String> lines) throws IOException {
        //Check the generated path. If it is not there, create it.
        if (!Paths.get("./generated").toFile().exists()) Files.createDirectories(Paths.get("./generated"));
        //Create Word docs.
        for (String line : lines) {
            //Blank Document
            XWPFDocument document = new XWPFDocument();
            //Write the Document in file system
            FileOutputStream out = new FileOutputStream("generated/" + "createdWord" + "_" + line + ".docx");
            //create Paragraph
            XWPFParagraph paragraph = document.createParagraph();
            XWPFRun run = paragraph.createRun();
            run.setText("VK Number (Parameter): " + line + " here you type your text...\n");
            document.write(out);
            //Close document
            out.close();
            System.out.println("createdWord" + "_" + line + ".docx" + " written successfully");
        }
    }
}

Main Class

import java.io.File;
import java.util.List;
import java.util.Objects;

public class Main {
    public static void main(String[] args) throws Exception {
        //Instantiate WordGenerator Class
        WordGenerator wg = new WordGenerator();

        //Gather VK Lines from text file
        List<String> vkLines = wg.getLines(
            new File((Objects.requireNonNull(Main.class.getClassLoader().getResource("vk_no.txt")).toURI())));

        //Create word document according to VK lines
        wg.createWord(vkLines);
    }
}

Input Text File

11111
22222
33333
44444
55555

Console Output and Result:

Github Project

https://github.com/swtestacademy/word-file-generator

Thanks,
Onur Baskirt

8 thoughts on “How to Create a Word Document with JAVA [2021 Update]”

    • Canberk, kesinlikle sana katılıyorum. POI, çok başarılı bir library. Ben de haftalık rutin yaptığım işlerdenen birinde excel’den data okumak için POI’yi kullanmıştım. Onu da ileride JAVA FX ile ilgili bir örnek yaparken yayınlayacağım.

      Reply
  1. Word veya excel üzerinde bir işlem yapacaksanız bir scripting dili olan Python kullanmak daha rahat oluyor.(Tabi özel bir program yazmıyorsanız.) Oradaki paketler de ücretsiz.

    Reply
  2. Hi, can you please help if we want to take excel sheet inplace of text file? Like how to read the specific column and all?

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.