Creating HTML from a DataTable using C#

41,388

Solution 1

Loop over your DataTable, and build up the html string. IE:

DataTable dt = new DataTable();

dt.Columns.Add("col1");
dt.Columns.Add("col2");
dt.Columns.Add("col3");
dt.Rows.Add(new object[] { "a", "b", "c" });
dt.Rows.Add(new object[] { "d", "e", "f" });

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>");

Solution 2

I just want to share what I did. I hope this would help.

using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;

public void Build(DataSet ds) 
{
    StringWriter sw = new StringWriter();
    HtmlTextWriter w = new HtmlTextWriter(sw);

    foreach (DataTable dt in ds.Tables) 
    {
        //Create a table
        Table tbl = new Table();

        //Create column header row
        TableHeaderRow thr = new TableHeaderRow();
        foreach (DataColumn col in dt.Columns) {
            TableHeaderCell th = new TableHeaderCell();
            th.Text = col.Caption;
            thr.Controls.Add(th);
        }
        tbl.Controls.Add(thr);

        //Create table rows
        foreach (DataRow row in dt.Rows)
        {
            TableRow tr = new TableRow();
            foreach (var value in row.ItemArray)
            {
                TableCell td= new TableCell();
                td.Text = value.ToString();
                tr.Controls.Add(td);
            }
            tbl.Controls.Add(tr);
        }

        tbl.RenderControl(w);

    }

    Response.Write(sw.ToString());
}

Solution 3

Code could be pretty long to write here, I agree with @mservidio. Follow this link to see an example of what you have to do: this link

Solution 4

how do i convert a datatable into an html table?

The only way is to write code that goes through every row and builds the HTML string the way you need it.

is there a better solution to my issue?

You could use a monospace font (such as Courier) wihch will allow you to align everything properly by simply outputting the right number of spaces but you'd still need to send the email in HTML format setting the proper font on the document.

Solution 5

public string ConvertDataTableToHTMLTableInOneLine(DataTable dt)
    {
        //Convert DataTable To HTML Table in one line
        return "<table>\n<tr>" + string.Join("", dt.Columns.Cast<DataColumn>().Select(dc => "<td>" + dc.ColumnName + "</td>")) + "</tr>\n" +
        "<tr>" + string.Join("</tr>\n<tr>", dt.AsEnumerable().Select(row => "<td>" + string.Join("</td><td>", row.ItemArray) + "</td>").ToArray()) + "</tr>\n<\table>";

    }
Share:
41,388
Alex Gordon
Author by

Alex Gordon

Check out my YouTube channel with videos on Azure development.

Updated on January 05, 2020

Comments

  • Alex Gordon
    Alex Gordon over 4 years

    I need to be able to pass HTML data into Outlook like this:

    MailMessage message = new MailMessage();
    message.Body = myBody;
    

    Initially, I thought I could pass plain text to it and use PadLeft like this:

    somestring.PadLeft(100);
    

    but it did not align everything properly because even though ||||| and MMMMM are both only 5 characters in length, they physically on the screen take up more space.

    My solution is to convert data that is in my datatable into an HTML table and then pass it into Outlook.

    1. how do I convert a datatable into an html table?
    2. is there a better solution to my issue?
  • Adriano Repetti
    Adriano Repetti about 12 years
    Side note: check your data, if they aren't numbers they may contain invalid characters for HTML so a raw ToString() doesn't work ("<" for example).
  • Alex Gordon
    Alex Gordon about 12 years
    thanks so much! i'm sorry my HTML is not great. how would i wrap the tags in there?
  • mservidio
    mservidio about 12 years
    I've updated the code snippet to show how to wrap it in the tags. See this url about using html tables: w3schools.com/html/html_tables.asp
  • Shai Cohen
    Shai Cohen about 12 years
    If it is simple, I would go with the answer presented by @mservidio
  • user3486773
    user3486773 about 8 years
    How could I add a border around the table using this code?
  • dipi evil
    dipi evil about 7 years
    He didin´t say JPG but HTML.