Word Files with XWPF

Harry · 24 Sep 2026 · 1 views
Log in to track your progress and mark lessons complete.

Reading a .docx File

import org.apache.poi.xwpf.usermodel.*;
import java.io.FileInputStream;

try (FileInputStream in = new FileInputStream("report.docx");
     XWPFDocument doc = new XWPFDocument(in)) {
    for (XWPFParagraph p : doc.getParagraphs())
        System.out.println(p.getText());
    doc.getTables().forEach(tbl -u003e tbl.getRows().forEach(row -u003e
        row.getTableCells().forEach(cell -u003e System.out.print(cell.getText() + " "))));
}

Reading paragraphs and tables from a Word document

Writing a .docx File

try (XWPFDocument doc = new XWPFDocument()) {
    XWPFParagraph title = doc.createParagraph();
    XWPFRun run = title.createRun();
    run.setText("Monthly Report");
    run.setBold(true);
    run.setFontSize(16);
    try (FileOutputStream out = new FileOutputStream("report.docx")) {
        doc.write(out);
    }
}

Full runnable version: ReadWordExample in the poi-examples repo. (Old binary .doc needs the separate poi-scratchpad artefact — prefer .docx.)

Share this post:

Comments (0)

Please login or register to comment.

Create a free account to keep reading

You've enjoyed a free tutorial! Register (it's free) to unlock every tutorial, track your progress and save code.

or sign in with your account

Already have an account? Log in