Copied RSS Feed

Word

How to Dynamically Fill Data in Word Table Using Java

Data is an important part of any application. Most of the time, data comes from a database or a file. To make our data easy to read and understand, we display it in a table.

Being developers, we often create dynamic and complex Word documents. We may generate complex tables that need to be filled from a data source, and we may not be sure about the exact rows and columns. Manually filling tables with data every time is a tedious task.

Our Syncfusion Java Word Library (Essential DocIO) is a feature-rich and high-performance library. It allows you to fill data in a Word table programmatically without Microsoft Word or any other interop dependencies on your side. We can generate a table at runtime by either using mail merge or appending the values one by one.

For example, if there is a need to generate a table in a Word document based on the data retrieved from a Web API, but we’re not sure about the rows and columns, then you can frame the data as a table using our Java Word Library.

You can then save the resultant document as a Word document (DOCX, WordML), or in HTML or RTF formats.

In this blog, we will see the following approaches to fill data in a table using the Java Word Library:

Note: If you are new to our Java Word Library (Essential DocIO), we highly recommend you take a look at our Getting Started guide.

How to configure the Syncfusion Java packages from the Maven repository in the Gradle project

First, we have to configure the Syncfusion Java packages from the Maven repository in the Gradle project:

Step 1: Create a new Gradle project.

Step 2: The New Gradle Project dialog will open. In that, provide the name for your project and click Finish.

Step 3: In the Package Explorer window, click the build.gradle file and include the following code to reference the Syncfusion Java packages from the Maven repository.

plugins 
{
    // Apply the java-library plugin to add support for Java Library.
    id 'java-library'
}

repositories 
{
    // Use jcenter for resolving your dependencies.
    jcenter()
    // You can declare any Maven/Ivy/file repository here.
    maven 
    {
     // Maven repository to download the artifacts.
     url "https://jars.syncfusion.com/repository/maven-public/"
    }
}
dependencies {
    implementation 'com.syncfusion:syncfusion-javahelper:19.2.0.55'
    implementation 'com.syncfusion:syncfusion-docio:19.2.0.55' 
}

Step 4: Now, the following Syncfusion .jar files will be downloaded from the Maven repository and added to your project, as shown in the following screenshot.

  • syncfusion-javahelper
  • syncfusion-docio

Thus, we have configured the Syncfusion Java packages from the Maven repository in your Gradle project. Let’s see the procedures to fill data in a table using the Syncfusion Java Word Library.

Fill data in a Word table dynamically by appending the values one by one

One of the simplest ways to construct a table at run time by appending the rows and cells is by using the addRow() and addCell() APIs.

The following code example illustrates filling the data in a Word table programmatically using the Java Word Library.

Include the javax.xml package in your project to process the XML documents.

import java.io.*;
import java.util.List;
import javax.xml.bind.*;
import com.syncfusion.docio.*;
import com.syncfusion.javahelper.system.*;
public static void main(String[] args) throws Exception 
{
 // Loads the XML file.
 File file = new File(getDataDir("StockDetails.xml"));
 // Create a new instance for the JAXBContext.
 JAXBContext jaxbContext = JAXBContext.newInstance(StockMarket.class);
 // Reads the XML file.
 Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
 StockMarket stockMarket = (StockMarket) jaxbUnmarshaller.unmarshal(file);
 // Gets the list of stock details.
 List<StockDetails> list =  stockMarket.getStockDetails();
 ListSupport<StockDetails> stockDetails =  new ListSupport<StockDetails>(StockDetails.class);  
 for(StockDetails stock : list) 
 {
  //Add all items in the list to ListSupport to perform mail merge. 
  stockDetails.add(stock);
 }
 // Loads the template document.
 WordDocument document = new WordDocument(getDataDir ("Template.docx"), FormatType.Docx);
 MailMergeDataTable dataTable = new MailMergeDataTable("StockDetails", stockDetails);
 // Executes Mail Merge with group.
 document.getMailMerge().executeGroup(dataTable);
 // Saves and closes the document.
 document.save("Result.docx", FormatType.Docx);
 document.close();
}

The following code example illustrates the helper class to hold the data from the XML file.

import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement(name = "Employees")
public class Employees 
{
 private List<Employee> Employee;

 /**
  * Gets the list of employees.
  */ @XmlElement(name = "Employee")
 public List<Employee> getEmployees() {
  return Employee;
 }

 /**
  * Sets the list of employees.
  * 
  * @param employee List of employee.
  */ public void setEmployees(List<Employee> employee) {
  this.Employee = employee;
 }

 /**
  * Initializes a new instance of the Employees class.
  */ public Employees() {
 }

 /**
  * Initializes a new instance of the Employees class with the specified list of
  * employees.
  * 
  * @param employees List of employee.
  */ public Employees(List<Employee> employees) {
  this.Employee = employees;
 }
}

import javax.xml.bind.annotation.*;
public class Employee 
{
 private String Name;
 private String Title;
 private String Address;
 private String HomePhone;
 private String Photo;

 @XmlElement(name = "Name")
 /**
  * Gets the employee name.
  */ public String getName() {
  return Name;
 }

 /**
  * Sets the employee name.
  * 
  * @param name Name of the employee.
  */ public void setName(String name) {
  this.Name = name;
 }

 @XmlElement(name = "Title")
 /**
  * Gets the designation of the employee.
  */ public String getTitle() {
  return Title;
 }

 /**
  * Sets the designation of the employee.
  * 
  * @param title Designation of the employee.
  */ public void setTitle(String title) {
  this.Title = title;
 }

 @XmlElement(name = "Address")
 /**
  * Gets the address of the employee.
  */ public String getAddress() {
  return Address;
 }

 /**
  * Sets the address of the employee.
  * 
  * @param address Address of the employee.
  */ public void setAddress(String address) {
  this.Address = address;
 }

 @XmlElement(name = "HomePhone")
 /**
  * Gets the contact number of the employee.
  */ public String getHomePhone() {
  return HomePhone;
 }

 /**
  * Sets the contact number of the employee.
  * 
  * @param homePhone Contact number of the employee.
  */ public void setHomePhone(String homePhone) {
  this.HomePhone = homePhone;
 }

 @XmlElement(name = "Photo")
 /**
  * Gets the photo of the employee.
  */ public String getPhoto() {
  return Photo;
 }

 /**
  * Sets the photo of the employee.
  * 
  * @param photo Photo of the employee.
  */ public void setPhoto(String photo) {
  this.Photo = photo;
 }

 /**
  * Initializes a new instance of the Employee class with the specified name,
  * title, address, contact number, and photo.
  * 
  * @param name      Name of the employee.
  * @param title     Designation of the employee.
  * @param address   Address of the employee.
  * @param homePhone Contact number of the employee.
  * @param photo     Photo of the employee.
  * 
  */ public Employee(String name, String title, String address, String homePhone, String photo) {
  this.Name = name;
  this.Title = title;
  this.Address = address;
  this.HomePhone = homePhone;
  this.Photo = photo;
 }

 /**
  * Initializes a new instance of the Employee class.
  */ public Employee() {
 }
}

By executing the previous code example, we will get a Word document like in the following screenshot.

Fill Data in Word Table Dynamically by Appending the Values One by One Using Java Word Library

Note: For more details, you can download the complete working example for Dynamic Table in Java Word Library.

Fill data in a Word table dynamically by using mail merge

You can also fill data in a table using the mail merge facility in our Java Word Library. It is useful when you generate reports like invoices, payroll, etc.

Take a moment to peruse the Working with mail merge documentation for more information about the mail merge functionality in the Syncfusion Java Word Library.

Mail merge process

The mail merge process involves three things:

  • Template Word document: This document contains the static or templated text and graphics along with the merge fields (placeholders) for replacing dynamic data.
  • Data source: Files or databases containing data to replace the merge fields in the template Word document.
  • Final merged document: This resultant document is a combination of the template Word document and the data from a data source. The mail merge process pulls the information from the data source and replaces the merge fields (placeholders) in your template Word document.

Let’s see how to generate a table through the mail merge process in a Java Word document using Syncfusion’s mail merge API.

Create a template Word document

We can create a template document in two ways:

  • Using a word editor application like Microsoft Word to insert the merge fields like in the following screenshot.
  • Using the Java Word Library to create a template document programmatically like in the following code example.
    //Creates an instance of a WordDocument. 
    WordDocument document = new WordDocument();
    //Adds one section and one paragraph to the document.
    document.ensureMinimal();
    //Sets page margins to the last section of the document.
    document.getLastSection().getPageSetup().getMargins().setAll(72);
    //Appends text to the last paragraph.
    document.getLastParagraph().getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Center);
    document.getLastParagraph().applyStyle(BuiltinStyle.Heading1);
    document.getLastParagraph().appendText("Stock Market exchange report.").getCharacterFormat().setFontSize(14);
    IWTable table  = document.getLastSection().addTable();
    table.resetCells(2, 6);
    //Appends text to the cells.
    table.getRows().get(0).getRowFormat().setBackColor(ColorSupport.fromArgb(24, 53,94));
    table.get(0, 0).addParagraph().appendText("Trade No");
    table.get(0, 1).addParagraph().appendText("Company name");
    table.get(0, 2).addParagraph().appendText("Cost Price of a Share");
    table.get(0, 3).addParagraph().appendText("Number of Shares");
    table.get(0, 4).addParagraph().appendText("Sales Price of a Share");
    table.get(0, 5).addParagraph().appendText("Net Profit/Loss");
    table.getRows().get(1).getRowFormat().setBackColor(ColorSupport.fromArgb(219,229,241));
    table.get(1, 0).addParagraph().appendField("TableStart:StockDetails", FieldType.FieldMergeField);
    //Append merge field to the cells.
    table.get(1, 0).getLastParagraph().appendField("TradeNo", FieldType.FieldMergeField);
    table.get(1, 1).addParagraph().appendField("CompanyName", FieldType.FieldMergeField);
    table.get(1, 2).addParagraph().appendText("$");
    table.get(1, 2).getLastParagraph().appendField("CostPrice", FieldType.FieldMergeField);
    table.get(1, 3).addParagraph().appendField("SharesCount", FieldType.FieldMergeField);
    table.get(1, 4).addParagraph().appendText("$");
    table.get(1, 4).getLastParagraph().appendField("SalesPrice", FieldType.FieldMergeField);
    table.get(1, 5).addParagraph().appendText("Net Profit/Loss");
    table.get(1, 5).getLastParagraph().appendField("TableEnd:StockDetails", FieldType.FieldMergeField);
    //Saves the Word document.
    document.save("Template.docx", FormatType.Docx);
    //Closes the Word document.
    document.close();

    The following screenshot illustrates the template Word document used to generate a table through mail merge functionality.

    Creating a Template Word Document Using Syncfusion Java Word Library

Execute mail merge

The following code example illustrates how to execute mail merge in the template Word document to generate a Word table at run time.

Include the javax.xml package in your project for processing the XML documents.

import java.io.*;
import java.util.List;
import javax.xml.bind.*;
import com.syncfusion.docio.*;
import com.syncfusion.javahelper.system.*;
public static void main(String[] args) throws Exception 
{
 // Loads the XML file.
 File file = new File(getDataDir("EmployeesList.xml"));
 // Creates a new instance for the JAXBContext.
 JAXBContext jaxbContext = JAXBContext.newInstance(Employees.class);
 // Reads the XML file.
 Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
 Employees employees = (Employees) jaxbUnmarshaller.unmarshal(file);
 // Gets the list of employee details.
 List<Employee> employeeList = employees.getEmployees();
 // Loads the template document.
 WordDocument document = new WordDocument(getDataDir("WordTable_Template.docx"));
 // Iterates each item in the list.
 for (Employee employee : employeeList) 
 {
  // Accesses the table in the document.
  IWTable table = document.getSections().get(0).getTables().get(0);
  // Initializes the paragraph and adds new row to the table.
  IWParagraph paragraph = null;
  table.addRow();
  // Gets the employee photo and converts that base64 string to bytes.
  byte[] bytes = ConvertSupport.fromBase64String(employee.getPhoto());
  ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
  int index = table.getRows().getCount();
  // Appends the picture to the first cell.
  table.getRows().get(index - 1).getCells().get(0).addParagraph().appendPicture(stream);
  // Appends the employee details in the second cell.
  paragraph = table.getRows().get(index - 1).getCells().get(1).addParagraph();
  paragraph.appendText(employee.getName() + "\n" + employee.getTitle() + "\n" + employee.getAddress() + "\n"
     + employee.getHomePhone());
 }
 // Saves and closes the document.
 document.save("Result.docx");
 document.close();
}

The following code example illustrates the helper class to hold the data from the XML file.

import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement(name = "StockMarket")
public class StockMarket 
{
 private List<StockDetails> StockDetails;

 @XmlElement(name = "StockDetails")
 /**
  * Gets the list of stock details.
  */ public List<StockDetails> getStockDetails() {
  return StockDetails;
 }

 /**
  * Sets the list of stock details.
  * 
  * @param stockDetails List of stock details.
  */ public void setStockDetails(List<StockDetails> listStockDetails) {
  this.StockDetails = listStockDetails;
 }

 /**
  * Initializes a new instance of the StockMarket class.
  */ public StockMarket() {
 }

 /**
  * Initializes a new instance of the StockMarket class with a specified list of
  * stock details.
  * 
  * @param stockDetails List of stock details.
  */ public StockMarket(List<StockDetails> stockDetails) {
  this.StockDetails = stockDetails;
 }
}


import javax.xml.bind.annotation.XmlElement;
public class StockDetails 
{
 private String TradeNo;
 private String CompanyName;
 private String CostPrice;
 private String SharesCount;
 private String SalesPrice;

 @XmlElement(name = "TradeNo")
 /**
  * Gets the trade number of the share.
  */ public String getTradeNo() {
  return TradeNo;
 }

 /**
  * Sets the trade number of the share.
  * 
  * @param tradeNo Trade number of the share.
  */ public void setTradeNo(String tradeNo) {
  this.TradeNo = tradeNo;
 }

 @XmlElement(name = "CompanyName")
 /**
  * Gets the company name of the share.
  */ public String getCompanyName() {
  return CompanyName;
 }

 /**
  * Sets the company name of the share.
  * 
  * @param companyName Company name of the share.
  */ public void setCompanyName(String companyName) {
  this.CompanyName = companyName;
 }

 @XmlElement(name = "SharesCount")
 /**
  * Gets the total shares count.
  */ public String getSharesCount() {
  return SharesCount;
 }

 /**
  * Sets the total shares count.
  * 
  * @param sharesCount Total shares count.
  */ public void setSharesCount(String sharesCount) {
  this.SharesCount = sharesCount;
 }

 @XmlElement(name = "CostPrice")
 /**
  * Gets the cost price of the share.
  */ public String getCostPrice() {
  return CostPrice;
 }

 /**
  * Sets the cost price of the share.
  * 
  * @param costPrice Cost price of the share.
  */ public void setCostPrice(String costPrice) {
  this.CostPrice = costPrice;
 }

 @XmlElement(name = "SalesPrice")
 /**
  * Gets the sales price of the share.
  */ public String getSalesPrice() {
  return SalesPrice;
 }

 /**
  * Sets the sales price of the share.
  * 
  * @param salesPrice Sales price of the share.
  */ public void setSalesPrice(String salesPrice) {
  this.SalesPrice = salesPrice;
 }

 /**
  * Initializes a new instance of the StockDetails class.
  */ public StockDetails() throws Exception {
 }

 /**
  * Initializes a new instance of the StockDetails class with the specified trade
  * number, company name, cost price, share count, and sales price.
  * 
  * @param tradeNo     Trade number of the share.
  * @param companyName Company name of the share.
  * @param costPrice   Cost price of the share.
  * @param sharesCount Total share count.
  * @param salesPrice  Sales price of the share.
  */ public StockDetails(String tradeNo, String companyName, String costPrice, String sharesCount, String salesPrice)
   throws Exception {
  this.TradeNo = tradeNo;
  this.CompanyName = companyName;
  this.CostPrice = costPrice;
  this.SharesCount = sharesCount;
  this.SalesPrice = salesPrice;
 }
}

By executing the previous code example, we will get a Word document like in the following screenshot.

Fill Data in Word Table Dynamically Using Mail Merge in Java Word Library

Note: For more details, you can download a complete example for Dynamic table using mail merge in the Java Word Library demo.

Easily build real-time apps with Syncfusion’s high-performance, lightweight, modular, and responsive JavaScript UI components.

Summary

Thanks for reading! In this blog, we have seen how to fill data in a Word table using the Syncfusion Java Word Library (DocIO). Take a moment to peruse the Working with Tables in Word document, where you’ll find other options and features, all with accompanying code examples. Try out the steps given in this blog post and leave your feedback in the comments section below!

Are you already a Syncfusion user? You can download the product setup here. If not, you can download a free, 30-day trial.

You can contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!

Recommended resources

If you like this blog post, we think you’ll also like the following articles:

Meet the Author

Sivasubramani V

Sivasubramani is Product manager at Syncfusion who has specialized skills in File Format products. He also loves working on new technology always and has been active since 2013.