How to Build a Table from a DataTable

Contents
[ ]

Often your application will pull data from a database and store it in the form of a DataTable. You may wish to easily insert this data into your document as a new table and quickly apply formatting to the whole table.

Using Aspose.Words this task is very simple to achieve. The code presented in this article demonstrates how to do this.

To build a table in a document from the data found in a DataTable:

  1. Create a new DocumentBuilder object on your Document.
  2. Start a new table using DocumentBuilder.
  3. If we want to insert the names of each of the columns from our DataTable as a header row then iterate through each data column and write the column names into a row in the table.
  4. Iterate through each DataRow in the DataTable.
    1. Iterate through each object in the DataRow.
    2. Insert the object into the document using DocumentBuilder. The method used depends on the type of the object being inserted e.g DocumentBuilder.writeln() for text and DocumentBuilder.insertImage() for a byte array which represents an image.
    3. At the end of processing of the data row also end the row being created by the [DocumentBuilder]https://apireference.aspose.com/words/java/com.aspose.words/DocumentBuilder) by using DocumentBuilder.endRow().
  5. Once all rows from the DataTable have been processed finish the table by calling DocumentBuilder.endTable().
  6. Finally, we can set the desired table style using one of the appropriate table properties such as Table.getStyleIdentifier() to automatically apply formatting to the entire table. The following data in our DataTable is used in this example:

todo:image_alt_text

The following code demonstrates how to achieve this in Aspose.Words. The ImportTableFromDataTable method accepts a DocumentBuilder object, the DataTable containing the data and a flag which specifies if the column heading from the DataTable are included at the top of the table. This method builds a table from these parameters using the builder’s current position and formatting. 

The following code example provides a method to import data from the DataTable and insert it into a new table using the DocumentBuilder.

The method can then be easily called using your DocumentBuilder and data.

The following code example shows how to import the data from a DataTable and insert it into a new table in the document.

The following table is produced by running the code above:

todo:image_alt_text