google-site-verification=ECX1M6_Vb39ty4VtQDXQce6wOjmPTxSettd3hTIZb9Q

C# - Convert Datatable to Html Format

random

C# - Convert Datatable to Html Format

.Net - Creating HTML from a DataTable using C#


In my previous article I explained about How can I send email from Gmail - ASP.Net. In this post I will show you how to convert a datatable to html format. Actually sometimes we have a scenario like I want to send email with some dynamic data from datatable. Find the source code below:

Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        BindDatatable();
    }

    /// <summary>
    /// Author: eTechPulse
    /// Description: Convert datatable to html format
    /// </summary>
   
    // Creating a dummy table
    private void BindDatatable()
    {
        DataTable dt = new DataTable();
      
        dt.Columns.Add("EmpId", typeof(int));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Address", typeof(string));
        dt.Columns.Add("Date", typeof(DateTime));

        //
        // Here we add five DataRows.
        //

        dt.Rows.Add(25, "Rk", "Gurgaon", DateTime.Now);
        dt.Rows.Add(50, "Sachin", "Noida", DateTime.Now);
        dt.Rows.Add(10, "Nitin", "Noida", DateTime.Now);
        dt.Rows.Add(21, "Aditya", "Meerut", DateTime.Now);
        dt.Rows.Add(100, "Mohan", "Banglore", DateTime.Now);

        string HtmlBody = ConvertToHtmlFile(dt);
        Response.Write(HtmlBody);
    }

    // Converting datatable to HTML string Sample 1
    public string ConvertDT2HTMLString(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>", System.Web.HttpUtility.HtmlEncode(o.ToString()));
            }
            sb.AppendLine("</tr>");
        }
        sb.AppendLine("</tbody></table></body></html>");
        return sb.ToString();
    }

Output:

Convert Datatable to Html Format

   
// Converting datatable to HTML string Sample 2
    private string ConvertDT2HTMLString2(DataTable dt)
    {
        string tab = "\t";

        StringBuilder sb = new StringBuilder();

        sb.AppendLine("<html>");
        sb.AppendLine(tab + "<body>");
        sb.AppendLine(tab + tab + "<table>");

        // headers.
        sb.Append(tab + tab + tab + "<tr>");

        foreach (DataColumn dc in dt.Columns)
        {
            sb.AppendFormat("<td>{0}</td>", dc.ColumnName);
        }

        sb.AppendLine("</tr>");

        // data rows
        foreach (DataRow dr in dt.Rows)
        {
            sb.Append(tab + tab + tab + "<tr>");

            foreach (DataColumn dc in dt.Columns)
            {
                string cellValue = dr[dc] != null ? dr[dc].ToString() : "";
                sb.AppendFormat("<td>{0}</td>", cellValue);
            }

            sb.AppendLine("</tr>");
        }

        sb.AppendLine(tab + tab + "</table>");
        sb.AppendLine(tab + "</body>");
        sb.AppendLine("</html>");

        return sb.ToString();
    }

Output:


    // Creating a HTML file from datatable with style
    public  string ConvertToHtmlFile(DataTable targetTable)
    {
        string myHtmlFile = "";      
       
        //Get a worker object.
        StringBuilder strBuilder = new StringBuilder();

        //Open tags and write the top portion.
        strBuilder.Append("<html xmlns='http://www.w3.org/1999/xhtml'>");
        strBuilder.Append("<head>");
        strBuilder.Append("<title>");
        strBuilder.Append("Page-");
        strBuilder.Append(Guid.NewGuid().ToString());
        strBuilder.Append("</title>");
        strBuilder.Append("</head>");
        strBuilder.Append("<body>");
        strBuilder.Append("<table border='1px' cellpadding='5' cellspacing='0' ");
        strBuilder.Append("style='border: solid 1px Silver; font-size: x-small;'>");
       
        //Add the headings row.

        strBuilder.Append("<tr align='left' valign='top'>");

        foreach (DataColumn myColumn in targetTable.Columns)
        {
            strBuilder.Append("<td align='left' valign='top'>");
            strBuilder.Append(myColumn.ColumnName);
            strBuilder.Append("</td>");
        }

        strBuilder.Append("</tr>");

        //Add the data rows.
        foreach (DataRow myRow in targetTable.Rows)
        {
            strBuilder.Append("<tr align='left' valign='top'>");

            foreach (DataColumn myColumn in targetTable.Columns)
            {
                strBuilder.Append("<td align='left' valign='top'>");
                strBuilder.Append(myRow[myColumn.ColumnName].ToString());
                strBuilder.Append("</td>");
            }
           
            strBuilder.Append("</tr>");
        }
       

        //Close tags.
        strBuilder.Append("</table>");
        strBuilder.Append("</body>");
        strBuilder.Append("</html>");

        //Get the string for return.
        myHtmlFile = strBuilder.ToString();
        return myHtmlFile;
    }   

Output:

C# - Convert Datatable to html file


}
Download the source code click here
Please leave your comments, suggestions and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. Thanks for reading!
C# - Convert Datatable to Html Format Reviewed by Ravi Kumar on 2:42 PM Rating: 5

1 comment:

All Rights Reserved by Etechpulse © 2012 - 2017

Contact Form

Name

Email *

Message *

Powered by Blogger.