Write a Microsoft Word File

This example shows how to write records to a Microsoft Word document. A MicrosoftWordWriter produces a .docx file containing a single table with a header row of field names and one row per record. The page size and orientation are configurable; the defaults are Letter and portrait, and this example switches to A4 landscape so the seven columns fit comfortably on the page.

Input CSV file

Account,LastName,FirstName,Balance,CreditLimit,AccountCreated,Rating
101,Reeves,Keanu,9315.45,10000.00,1/17/1998,A
312,Butler,Gerard,90.00,1000.00,8/6/2003,B
868,Hewitt,Jennifer Love,0,17000.00,5/25/1985,B
761,Pinkett-Smith,Jada,49654.87,100000.00,12/5/2006,A
317,Murray,Bill,789.65,5000.00,2/5/2007,C

Java Code Listing

package com.northconcepts.datapipeline.examples.microsoftword;

import java.io.File;

import com.northconcepts.datapipeline.core.DataReader;
import com.northconcepts.datapipeline.core.DataWriter;
import com.northconcepts.datapipeline.csv.CSVReader;
import com.northconcepts.datapipeline.job.Job;
import com.northconcepts.datapipeline.microsoft.word.MicrosoftWordWriter;
import com.northconcepts.datapipeline.microsoft.word.MicrosoftWordWriter.PageOrientation;
import com.northconcepts.datapipeline.microsoft.word.MicrosoftWordWriter.PageSize;

public class WriteAMicrosoftWordFile {

    public static void main(String[] args) {
        DataReader reader = new CSVReader(new File("example/data/input/credit-balance-01.csv"))
                .setFieldNamesInFirstRow(true);

        DataWriter writer = new MicrosoftWordWriter(new File("example/data/output/credit-balance-01.docx"))
                .setPageSize(PageSize.A4)
                .setPageOrientation(PageOrientation.LANDSCAPE);

        Job.run(reader, writer);
    }

}

Code Walkthrough

  1. A CSVReader reads credit-balance-01.csv with field names in the first row.
  2. A MicrosoftWordWriter is created for the output file example/data/output/credit-balance-01.docx. setPageSize(PageSize.A4) selects the paper size (LETTER, LEGAL, LEDGER, A3, A4, A5, JIS_B4 and JIS_B5 are available) and setPageOrientation(PageOrientation.LANDSCAPE) turns the page.
  3. Job.run() transfers the records; the document is written when the writer closes.

Output Word file

credit-balance-01.docx opens in Word or LibreOffice as a landscape A4 page holding a table with seven columns: a header row of field names followed by the five records.

Mobile Analytics