Build a Table from a `DataTable`
Contents
[
Hide
]
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.
Note that the preferred way of inserting data from a DataTable into a document table is by using Mail Merge with Regions. The technique presented in this article is only suggested if you are unable to create a suitable template beforehand to merge data with, in other words, if you require everything to happen programmatically.
Using Aspose.Words, you can easily retrieve data from a database and store it as a table:
- Create a new DocumentBuilder object on your Document.
- Start a new table using DocumentBuilder.
- 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.
- Iterate through each DataRow in the DataTable:
- Iterate through each object in the DataRow.
- 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.
- At the end of processing of the data row also end the row being created by the DocumentBuilder by using DocumentBuilder.endRow().
- Once all rows from the DataTable have been processed finish the table by calling DocumentBuilder.endTable().
- 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:
The following code example shows how to execute the above algorithm in Aspose.Words:
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 table shown in the picture below is produced by running the above code.