DEV Community

loading...

Java generate word document automatically

eiceblue profile image E-iceblue Product Family ・3 min read

I need to generate MS word documents automatically in my Java applications. So I started to search how to accomplish this task and found Spire.Doc for Java. We can easily work with MS Word documents (doc, docx, wordml, wordxml, odt, docm, dotm, dotx, dot etc) with Spire.Doc library.
Adding Spire.Doc.jar as a dependency. Firstly, download Free Spire.Doc for Java 2.7.3. Unzip it, and you’ll get the jar file from the ‘lib’ folder. Secondly, create a Java application in your IDE. Import the jar file in your project as a dependency.
Now, let’s go with JAVA codes to create a Word template.

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.DropDownFormField;

public class createWordTemplate {

    public static void main(String[] args) {
        //create a Word document and add a section
        Document doc = new Document();
        Section section = doc.addSection();

        //add a table
        Table table = section.addTable();
        table.resetCells(4, 2);
        table.applyStyle(DefaultTableStyle.Colorful_List);
        table.getTableFormat().getBorders().setBorderType(BorderStyle.Single);

        //add text to the cells of the first column
        Paragraph paragraph = table.getRows().get(0).getCells().get(0).addParagraph();
        paragraph.appendText("Name");
        paragraph = table.getRows().get(1).getCells().get(0).addParagraph();
        paragraph.appendText("Date");
        paragraph = table.getRows().get(2).getCells().get(0).addParagraph();
        paragraph.appendText("Gender");
        paragraph = table.getRows().get(3).getCells().get(0).addParagraph();
        paragraph.appendText("Image");

        //add a text form to the specific cell
        paragraph = table.getRows().get(0).getCells().get(1).addParagraph();
        paragraph.appendText("{#}");

        //add a text field to the specific cell
        paragraph = table.getRows().get(1).getCells().get(1).addParagraph();
        paragraph.appendField("Date", FieldType.Field_Merge_Field);

        //add a dropdown-list form to the specific cell
        paragraph = table.getRows().get(2).getCells().get(1).addParagraph();
        DropDownFormField dropdownField = (DropDownFormField)paragraph.appendField("listbox",FieldType.Field_Form_Drop_Down);
        dropdownField.getDropDownItems().add("Male");
        dropdownField.getDropDownItems().add("Female");

        //add an image field to the specific cell
        paragraph = table.getRows().get(3).getCells().get(1).addParagraph();
        paragraph.appendField("Image:Photo", FieldType.Field_Merge_Field);

        //create a ParagraphStyle object
        ParagraphStyle style = new ParagraphStyle(doc);
        style.setName("newFont");
        style.getCharacterFormat().setFontName("Calibri");
        style.getCharacterFormat().setFontSize(13);
        doc.getStyles().add(style);

        for (int i = 0; i < table.getRows().getCount(); i++) {

            //set row height
            table.getRows().get(i).setHeight(30f);

           for (Object cell:table.getRows().get(i).getCells()){
                if (cell instanceof TableCell)
                {
                    //set the vertical alignment of each cell to middle
                    ((TableCell) cell).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
                    //apply paragraph style to each cell
                    ((TableCell) cell).getParagraphs().get(0).applyStyle(style.getName());
                }
            }
        }

            //save to file
            doc.saveToFile("out/Template.docx", FileFormat.Docx_2013);
        }
    }

Word Template:
Word Template

After I get a Word template with table, which contains image field, text field and dropdown list field. Then I can get a large amount of Word document with the same template by replacing text and filling the fields.

import com.spire.doc.*;
import com.spire.doc.reporting.MergeImageFieldEventArgs;
import com.spire.doc.reporting.MergeImageFieldEventHandler;
import java.text.SimpleDateFormat;
import java.util.Date;

public class wordMailmerge {

    public static void main(String[] args) throws Exception {
        //load the sample document
        Document doc = new Document();
        doc.loadFromFile("Template.docx");

        //find a specific string and replace it with other string
        doc.replace("{#}", "John", false, true);

        //merge the text field
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        String[] fieldName = new String[]{"Date"};
        String[] fieldValue = new String[]{ dateString};
        doc.getMailMerge().execute(fieldName, fieldValue);

        //merge image field
        String[] filedNames = new String[]{"Photo"};
        String[] filedValues = new String[]{"Image.png"};
        doc.getMailMerge().MergeImageField = new MergeImageFieldEventHandler() {
           public void invoke(Object sender, MergeImageFieldEventArgs args) {
                mailMerge_MergeImageField(sender, args);
            }
        };
        doc.getMailMerge().execute(filedNames, filedValues);
        doc.saveToFile("MailMergeImage.docx", FileFormat.Docx_2013);
            }
    private static void mailMerge_MergeImageField(Object sender, MergeImageFieldEventArgs field) {

        String filePath = field.getImageFileName();
        if (filePath != null && !"".equals(filePath)) {
            try {
                field.setImage(filePath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

After merge the text field and image field, I get the Word document automatically with the same Word template:

Result

I will introduce more word functions on Java platform in the future.

Discussion (0)

pic
Editor guide