Objective
When we export data in C #, we need the output data in HTML format, we need to use the method of exporting DataTable to HTML format, the following code can help us to achieve the purpose.
First, we will bind the DataTable and DataGridView.
I. Binding DataGridView through a DataTable
1. Create a DataTable, add columns
DataTable table = new DataTable (); table. Columns.Add ("ID", typeof (int)), table. Columns.Add ("NAME", typeof (String)), table. Columns.Add ("City", typeof (String));
2. Add Rows again
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. Binding DataGridView
datagridview1.datasource=table;
4. Running Results
Ii. Exporting a DataTable to HTML
I wrote a set of code to create HTML text for each DataTable. You can refer directly to it in your project.
The code is as follows:
Protected string exportdatatabletohtml (DataTable dt) {StringBuilder Strhtmlbuilder = new StringBuilder (); Strhtmlbuilder.append ("
Third, code understanding
We created a function that uses a DataTable as a parameter.
Then use the StringBuilder class to create Dynamic HTML text.
The output results are the same as the number of rows and columns in DataGridView.
Create columns in HTML.
foreach (DataColumn myColumn in dt. Columns) {strhtmlbuilder.append ("<TD >"); strhtmlbuilder.append (mycolumn.columnname); Strhtmlbuilder.append ( "</td>"); }
Copy the data, the following code creates the same number of rows in the DataTable and copies the data to the HTML line.
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>");}
Iv. execute the above code and get the following HTML text
V. Create HTML files
String HtmlBody = exportdatatabletohtml (table) System.IO.File.WriteAllText (@ "C:\ABC. HTML ", HtmlBody);
Vi. Results of operation
Summarize
The above is about C # in the export of the DataTable to HTML format of all the content, I hope that the content of this article on everyone's study or work can bring some help, if there is doubt you can message exchange.