Friday, October 19, 2012

Populating an existing excel table from a datatable using ClosedXML

There is a better way of creating excel 2007/2010 reports in .net. Rather than using OpenXML use ClosedXML. Coding is a lot faster with ClosedXML. Below is an example on how to populate an existing excel table from a datatable.

if (table.Rows.Count > 0)
                    wstable.InsertRowsBelow(table.Rows.Count - 1);
                    var excelrow = wstable.DataRange.FirstRow();
                    int loop = 1;                    
                    foreach (DataRow row in table.Rows)
                        foreach (DataColumn column in table.Columns)
                            excelrow.Field(column.ColumnName).Value = row[column.ColumnName];
                        loop = loop + 1;
                        excelrow = wstable.DataRange.Row(loop);
The example above assumes that the datatable contains the same column names with the excel table.

You can download the library from

No comments:

Post a Comment