JavaRanch Home    
This page:         last edited 22 March 2009         What's Changed?         Edit

Create Word Document   

This program shows how to use Apache POI HWPF to create a Word document. It sets various font and paragraph properties (like bold, italic, center alignment and first line indent), and adds a custom document property. For more options, check out the JavaDoc:org.apache.poi.hwpf.usermodel.Paragraph and JavaDoc:org.apache.poi.hwpf.usermodel.CharacterRun classes. For some reason, HWPF can't create a document from scratch, so an empty document ('empty.doc') needs to be present when the code is run.


import org.apache.poi.hpsf.CustomProperties;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class CreateWordDoc {

    public static void main (String[] args) throws Exception {
        // POI apparently can't create a document from scratch,
        // so we need an existing empty dummy document
        POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("empty.doc"));
        HWPFDocument doc = new HWPFDocument(fs);

        // centered paragraph with large font size
        Range range = doc.getRange();
        Paragraph par1 = range.insertAfter(new ParagraphProperties(), 0);
        // justification: 0=left, 1=center, 2=right, 3=left and right

        CharacterRun run1 = par1.insertAfter("one");
        run1.setFontSize(2 * 18);
        // font size: twice the point size

        // paragraph with bold typeface
        Paragraph par2 = run1.insertAfter(new ParagraphProperties(), 0);
        CharacterRun run2 = par2.insertAfter("two two two two two two two two two two two two two");

        // paragraph with italic typeface and a line indent in the first line
        Paragraph par3 = run2.insertAfter(new ParagraphProperties(), 0);
        CharacterRun run3 = par3.insertAfter("three three three three three three three three three "
            + "three three three three three three three three three three three three three three "
            + "three three three three three three three three three three three three three three");

        // add a custom document property (needs POI 3.5; POI 3.2 doesn't save custom properties)
        DocumentSummaryInformation dsi = doc.getDocumentSummaryInformation();
        CustomProperties cp = dsi.getCustomProperties();
        if (cp == null)
            cp = new CustomProperties();
        cp.put("myProperty""foo bar baz");

        doc.write(new FileOutputStream("new-hwpf-file.doc"));

CategoryCodeSamples CodeBarn

JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton