color: #ff0000">前言
在C#中DataTable导出数据的时候,我们需要HTML格式的输出数据, 这时候就需要使用将DataTable导出为到HTML格式的方法了,以下代码就可以帮助我们达到目的。
首先,我们要绑定DataTable和 DataGridView。
一、通过DataTable绑定DataGridView
1. 创建DataTable,添加列
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("NAME", typeof(string));
table.Columns.Add("CITY", typeof(string));
2. 再添加行
table.Rows.Add(111, "Devesh", "Ghaziabad");
table.Rows.Add(222, "ROLI", "KANPUR");
table.Rows.Add(102, "ROLI", "MAINPURI");
table.Rows.Add(212, "DEVESH", "KANPUR");
3. 绑定DataGridView
dataGridView1.DataSource=table;
4. 运行结果

二、将DataTable 导出为 HTML
我写了一组代码来为每个DataTable创建HTML文本。你可以在你的项目中直接引用。
代码如下:
protected string ExportDatatableToHtml(DataTable dt)
{
StringBuilder strHTMLBuilder = new StringBuilder();
strHTMLBuilder.Append("<html >");
strHTMLBuilder.Append("<head>");
strHTMLBuilder.Append("</head>");
strHTMLBuilder.Append("<body>");
strHTMLBuilder.Append("<table border='1px' cellpadding='1' cellspacing='1' bgcolor='lightyellow' style='font-family:Garamond; font-size:smaller'>");
strHTMLBuilder.Append("<tr >");
foreach (DataColumn myColumn in dt.Columns)
{
strHTMLBuilder.Append("<td >");
strHTMLBuilder.Append(myColumn.ColumnName);
strHTMLBuilder.Append("</td>");
}
strHTMLBuilder.Append("</tr>");
foreach (DataRow myRow in dt.Rows)
{
strHTMLBuilder.Append("<tr >");
foreach (DataColumn myColumn in dt.Columns)
{
strHTMLBuilder.Append("<td >");
strHTMLBuilder.Append(myRow[myColumn.ColumnName].ToString());
strHTMLBuilder.Append("</td>");
}
strHTMLBuilder.Append("</tr>");
}
//Close tags.
strHTMLBuilder.Append("</table>");
strHTMLBuilder.Append("</body>");
strHTMLBuilder.Append("</html>");
string Htmltext = strHTMLBuilder.ToString();
return Htmltext;
}
三、代码理解
我们创建了一个函数,使用DataTable作为参数。
然后用stringbuilder类创建动态的HTML文本。
输出结果与DataGridView中的行和列数量相同。










