Render DataTable as HTML Table


This is a fairly simple c# function to convert any DataTable into HTML table. This function works perfectly well with iqy file feeding tabular data into Excel.

    public static string ConvertDataTable2HTMLString(DataTable dt)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("<html><body><table><thead><tr>");
        foreach (DataColumn c in dt.Columns)
        {
            sb.AppendFormat("<th>{0}</th>", c.ColumnName);
        }
        sb.AppendLine("</tr></thead><tbody>");
        foreach (DataRow dr in dt.Rows)
        {
            sb.Append("<tr>");
            foreach (object o in dr.ItemArray)
            {
                sb.AppendFormat("<td>{0}</td>", Server.HtmlEncode(o.ToString()));
            }
            sb.AppendLine("</tr>");
        }
        sb.AppendLine("</tbody></table></body></html>");
        return sb.ToString();
    }

 

Here’s the sample iqy Excel file to query data that are in HTML table format

WEB
1
http://url/PATH/script.aspx

2 thoughts on “Render DataTable as HTML Table

  1. I just couldn’t leave your web site before suggesting that I extremely enjoyed the usual info a person supply in your guests? Is gonna be back ceaselessly to check out new posts

Leave a comment