Creating HTML from a DataTable using C#
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>");
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());
}
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