Tables are one of the most common ways to display structured data in documents. GroupDocs.Assembly for .NET makes it easy to generate dynamic tables by iterating over collections and populating table rows with data.
The :"C" format string formats the price as currency.
Generate Table from DataTable
You can also generate tables from ADO.NET DataTable:
usingGroupDocs.Assembly;usingSystem.Data;publicstaticvoidGenerateTableFromDataTable(){// Create DataTableDataTableproductsTable=newDataTable("Products");productsTable.Columns.Add("Name",typeof(string));productsTable.Columns.Add("Price",typeof(decimal));productsTable.Columns.Add("Quantity",typeof(int));// Add rowsproductsTable.Rows.Add("Laptop",999.99m,5);productsTable.Rows.Add("Mouse",29.99m,20);productsTable.Rows.Add("Keyboard",79.99m,15);DocumentAssemblerassembler=newDocumentAssembler();assembler.AssembleDocument("TableTemplate.docx","DataTableOutput.docx",newDataSourceInfo(productsTable,"products"));Console.WriteLine("Table generated from DataTable successfully.");}
Generate Table with Totals
Add a total row after the data rows:
usingGroupDocs.Assembly;usingSystem.Collections.Generic;publicstaticvoidGenerateTableWithTotals(){List<Product>products=newList<Product>{newProduct{Name="Laptop",Price=999.99m,Quantity=5},newProduct{Name="Mouse",Price=29.99m,Quantity=20},newProduct{Name="Keyboard",Price=79.99m,Quantity=15}};DocumentAssemblerassembler=newDocumentAssembler();assembler.AssembleDocument("TableWithTotalsTemplate.docx","TableWithTotals.docx",newDataSourceInfo(products,"products"));Console.WriteLine("Table with totals generated successfully.");}
Template structure:
Product Name
Price
Quantity
<<foreach [in products]>><<[Name]>>
<<[Price]:"C">>
<<[Quantity]>><</foreach>>
Total
<<[products.Sum(p => p.Price)]:"C">>
<<[products.Sum(p => p.Quantity)]>>
Generate Table in Spreadsheet
Tables work similarly in spreadsheet templates:
usingGroupDocs.Assembly;usingSystem.Collections.Generic;publicstaticvoidGenerateTableInSpreadsheet(){List<Product>products=newList<Product>{newProduct{Name="Laptop",Price=999.99m,Quantity=5},newProduct{Name="Mouse",Price=29.99m,Quantity=20}};DocumentAssemblerassembler=newDocumentAssembler();assembler.AssembleDocument("TableTemplate.xlsx","TableOutput.xlsx",newDataSourceInfo(products,"products"));Console.WriteLine("Table generated in spreadsheet successfully.");}
The worksheet holds the same header row and data band row as the Word table, in plain cells.
Warning
In spreadsheet templates, the data band is a range of cells: the band opens in the first cell of the row and closes in its last cell, and the row is repeated for each item. The cells need no Excel table around them.
Advanced Usage Topics
To learn more about filtering, sorting, grouping table data, conditional table rows, and advanced table formatting, please refer to the advanced usage section.
More resources
GitHub Examples
You may easily run the code above and see the feature in action in our GitHub examples: