Free Support Forum -

How to dynamically insert tables

Hi, I am currently using Aspose Word to generate a word document that requires a table insertion. However, I cannot find some sample code that will dynamically build the table off of a data table, result set, or array. Could you point me in the direction of finding this, or perhaps provide it for me?

At the moment there are three ways to get tables inserted into your documents: using mail merge with regions, using DocumentBuilder or building a table from nodes directly.

1. Using mail merge with regions. With this approach you actually design the table in MS Word (great visual designer for your document by the way, much better than any direct document programming). In the table you normally would create and format just a header row and one data row. The single data row should contain merge fields. In addition to normal merge fields that correspond to your data table columns, two extra merge fields with special names "TableStart:MyTableName" and "TableEnd:MyTableName" are needed in that row. Then you open the document with Aspose.Word and execute Document.MailMerge.ExecuteWithRegions and pass a data table or other data set. Aspose.Word grows the table inside the document. For examples on how to do this see the demo project included with Aspose.Word installer.

2. The DocumentBuilder class provides methods that help you build a table at runtime quickly. The methods are InsertCell, StartTable, EndTable, EndRow etc. There is a demo of this in the Aspose.Word.Demos project too. There is even one example that shows how to combine mail merge and document builder to create a table with alternating row colors.

3. Using document nodes directly is also a possibility. You can just create Table, add some Row objects, add Cell objects. Add Paragraph objects into the cells and add Run objects into the paragraphs. DocumentBuilder essentially does all that, just provides a facade to do this simpler.

In the future we plan to add another method to create tables from your data quickly. It will take a data source and a table style and will automatically create a table for you so that you will not need to use mail merge or direct document programming/