Vorwort
Beim Exportieren von Daten aus DataTable in C# benötigen wir Ausgabedaten im HTML-Format. Zu diesem Zeitpunkt müssen wir die Methode zum Exportieren von DataTable in das HTML-Format verwenden Dies. Zweck.
Zuerst müssen wir DataTable und DataGridView binden.
1. DataGridView über DataTable binden
1. DataTable erstellen und Spalten hinzufügen
DataTable table = new DataTable(); table.Columns.Add("ID", typeof(int)); table.Columns.Add("NAME", typeof(string)); table.Columns.Add("CITY", typeof(string));
2. Zeilen hinzufügen
table.Rows.Add(111, "Devesh", "Ghaziabad"); table.Rows.Add(222, "ROLI", "KANPUR"); table.Rows.Add(102, "ROLI", "MAINPURI"); table.Rows.Add(212, "DEVESH", "KANPUR");
dataGridView1.DataSource=table;
Ich habe eine Reihe von Code geschrieben, um HTML-Text für jede DataTable zu erstellen. Sie können direkt in Ihrem Projekt darauf verweisen. Der Code lautet wie folgt:
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; }
foreach (DataColumn myColumn in dt.Columns) { strHTMLBuilder.Append("<td >"); strHTMLBuilder.Append(myColumn.ColumnName); strHTMLBuilder.Append("</td>"); }
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>"); }
<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>
string HtmlBody = ExportDatatableToHtml(table) System.IO.File.WriteAllText(@"c:\abc.HTML", HtmlBody);