Export DataTable to HTML in C#

Generate HTML table from DataTable instance in C#

When I searched for exporting s to HTML table in C# I found a lot of articles and code snippets which are basically doing string concatenation or String.Format on the hard-coded HTML String to generate HTML string of the table.

To me this approach is a bit like a workaround and I was never a fan of hard-coding values. In addition, code with a lot of hard-coded value end up as hardly maintainable code. So what is the different way of doing it?

Well, .NET comes with a lot of build in classes for rendering HTML content which are mainly developed for old WebForms back in the days where Microsoft wanted to make web development as similar possible to WindowsForms gaining a bigger audience of developers who were already comfortable with WindowsForms approach.

The truth is these classes are rarely used now-days, but they still exists as a part of System.Web.dll assembly. So why don't we use then to make this approach completely objet oriented and easy to maintain instead of long hard-coded sausage strings in our code.

using System;
using System.Data;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;

namespace DataTableExport
{
    public static class Extensions
    {
        public static String GetHtml(this DataTable dataTable)
        {
            StringBuilder sbControlHtml = new StringBuilder();
            using (StringWriter stringWriter = new StringWriter())
            {
                using (HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter))
                {
                    using (var htmlTable = new HtmlTable())
                    {
                        // Add table header row
                        using (var headerRow = new HtmlTableRow())
                        {
                            foreach (DataColumn dataColumn in dataTable.Columns)
                            {
                                using (var htmlColumn = new HtmlTableCell())
                                {
                                    htmlColumn.InnerText = dataColumn.ColumnName;
                                    headerRow.Cells.Add(htmlColumn);
                                }
                            }
                            htmlTable.Rows.Add(headerRow);
                        }

                        // Add data rows
                        foreach (DataRow row in dataTable.Rows)
                        {
                            using (var htmlRow = new HtmlTableRow())
                            {
                                foreach (DataColumn column in dataTable.Columns)
                                {
                                    using (var htmlColumn = new HtmlTableCell())
                                    {
                                        htmlColumn.InnerText = row[column].ToString();
                                        htmlRow.Cells.Add(htmlColumn);
                                    }
                                }
                                htmlTable.Rows.Add(htmlRow);
                            }
                        }
                        htmlTable.RenderControl(htmlWriter);
                        sbControlHtml.Append(stringWriter.ToString());
                    }
                }
            }
            return sbControlHtml.ToString();
        }
    }
}

    
Note

regardless of whether you are building a Web, Desktop, Console or Windows Service application you need to add reference to System.Web to the project where your extension method class sits in order to have System.Web.UI.HtmlControls namespace and its classes available

To make the method easier to use I prefer to implement it as an Extension Method which makes method available direly on the DataTable instance level.

Now to make a test, we first need to add using of DataTableExport namespace in our application code to make extension method available on the DataTable class instance. Next thing is to populate sample DataTable instance with sample data.

using System;
using System.Data;
using DataTableExport;
namespace SampleApplication
{
class Program
{
static void Main(string[] args)
{
var dataTable = new DataTable();
dataTable.Columns.Add("id");
dataTable.Columns.Add("Name");
dataTable.Columns.Add("Email");
var row = dataTable.NewRow();
row["id"] = Guid.NewGuid().ToString();
row["Name"] = "Bruce Wayne";
row["Email"] = "batman@superheroes.com";
dataTable.Rows.Add(row);

            row = dataTable.NewRow();
            row["id"] = Guid.NewGuid().ToString();
            row["Name"] = "Clark Kent";
            row["Email"] = "superman@superheroes.com";
            dataTable.Rows.Add(row);

            row = dataTable.NewRow();
            row["id"] = Guid.NewGuid().ToString();
            row["Name"] = "Peter Parker";
            row["Email"] = "spiderman@superheroes.com";
            dataTable.Rows.Add(row);

            dataTable.AcceptChanges();

            var html = dataTable.GetHtml();
        }
    }
}

    

The result of the GetHtml extension method call will be nicely formated table HTML string with the data from DataTable class instance.

<table>
	<tr>
		<td>id</td>
		<td>Name</td>
		<td>Email</td>
	</tr>
	<tr>
		<td>b5beceae-88b9-48cc-8813-adfade92ad45</td>
		<td>Bruce Wayne</td>
		<td>batman@superheroes.com</td>
	</tr>
	<tr>
		<td>1e7a12f6-2c01-4991-82d7-cbda23dd7a6a</td>
		<td>Clark Kent</td>
		<td>superman@superheroes.com</td>
	</tr>
	<tr>
		<td>74875789-853f-481e-8e7d-94b95e662d10</td>
		<td>Peter Parker</td>
		<td>spiderman@superheroes.com</td>
	</tr>
</table>

    

This is a basic implementation which will only produce table HTML string without any CSS style, but classes in System.Web.UI.HtmlControls provide method and properties for applying the CSS styles and standard and custom attributes to all HTML tag representation classes. More on this namespace classes you can find on Microsoft MSDN page.

References

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform includion ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article