今天我要向大家分享一种将DataTable导出为到HTML格式的方法.有时我们需要HTML格式的输出数据, 以下代码就可以帮助我们达到目的,。
首先,我们要绑定DataTable和 DataGridView。
A. 通过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. 运行结果
B. 将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; }C. 代码理解
我们创建了一个函数,使用DataTable作为参数。然后用stringbuilder类创建动态的HTML文本。输出结果与DataGridView中的行和列数量相同。在HTML中创建列。 foreach (DataColumn myColumn in dt.Columns) { strHTMLBuilder.Append("<td >"); strHTMLBuilder.Append(myColumn.ColumnName); strHTMLBuilder.Append("</td>"); } 复制数据,以下代码就会在DataTable中创建相同数量的行,并将数据复制到HTML行中。 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>"); }D. 执行上面的代码后得到如下HTML文本
<html > <head> </head> <body> <table border='1px' cellpadding='1' cellspacing='1' bgcolor='lightyellow' style='font-family:Garamond; font-size:smaller'> <tr > <td >ID</td> <td >NAME</td> <td >CITY</td> </tr><tr > <td >111</td><td >Devesh</td> <td >Ghaziabad</td></tr> <tr ><td >222</td><td >ROLI</td> <td >KANPUR</td></tr><tr > <td >102</td><td >ROLI</td> <td >MAINPURI</td></tr><tr > <td >212</td><td >DEVESH</td> <td >KANPUR</td></tr></table> </body> </html>E. 创建HTML文件
string HtmlBody = ExportDatatableToHtml(table) System.IO.File.WriteAllText(@"c:\abc.HTML", HtmlBody);F. 运行结果
转载于:https://www.cnblogs.com/Yesi/p/5896773.html