Create a word merge document using a CSV

i have the word api for java. Im looking for examples of creating a merge document using a CSV file. Can someone point me to examples?

Hi Tim,

Thanks for your inquiry. You can use MailMergeSettings object to specify a mail merge data source for a document and this information (along with the available data fields) will appear in Microsoft Word when the user opens this document. You can also use this object to query mail merge settings that the user has specified in Microsoft Word for this document.

Please check the following code example. Hope this helps you.

Could you please share some more detail about your requirements along with input document? We will then provide you more information about your query.

Document doc = new Document(MyDir + "in.docx");
doc.getMailMergeSettings().clear();

String query = "SELECT * FROM 'csvdata'";

MailMergeSettings mms = doc.getMailMergeSettings();
mms.setMainDocumentType(MailMergeMainDocumentType.MAILING_LABELS);
mms.setDataType(MailMergeDataType.NATIVE);
mms.setDataSource("C:\\Temp\\csvdata.csv");

mms.setQuery(query);
mms.setLinkToQuery(false);
mms.setViewMergedData(true);

doc.save(MyDir + "Output.docx");

i have attached a word document and a csv file that i use. Basically, i want to use the csv as the datasource to populate the word document merge fields. I dont need any sql selection since the word document has criteria in it to handle that.

i know this is probably an easy solution. just new to java and your great api.

Hi Tim,

Thanks for your inquiry. The simplest way to achieve your requirement is to read your CSV file into a ResultSet and then use this ResultSet as a data source for mail merge. Please read following documentation links. Hope this helps you.

About Mail Merge

Hi,

Could you provide a simple sample of code. New to java here

Hi Tim,

Thanks for your inquiry. We are working over your query and will get back to you soon.
Hi Tim,

Thanks for your patience. Please use following code example to convert csv into DataTable and perform mail merge. Hope this helps you.

DataTable dataTable = new DataTable();
Boolean header = true;

org.apache.commons.csv.CSVParser csvReader = new org.apache.commons.csv.CSVParser(new FileReader(MyDir + "test.csv"));
String[] content;
while((content = csvReader.getLine()) != null)
{

if(header)
{
for(int i=0; i < content.length; i++)
{
dataTable.getColumns().add(content[i]);
}
header = false;
}
else
{
DataRow dataRow = dataTable.newRow();
dataRow.setItemArray(content);
dataTable.getRows().add(dataRow);
}
}

Document doc = new Document(MyDir + "test.doc");
doc.getMailMerge().execute(dataTable);

doc.save(MyDir + "Out v16.10.0.docx");