How to Convert DataTable to Html Table in C#

By FoxLearn 7/18/2024 7:53:41 AM   5.88K
Converting a DataTable to an HTML table in a C# Windows Forms Application involves generating the HTML markup based on the data structure within the DataTable.

How to Convert DataTable to Html Table in C#

Convert a DataTable to an HTML table in C# Windows Forms involves iterating over the rows and columns of the DataTable and constructing the HTML markup accordingly.

Drag and drop the DataGridView, Button controls from the Visual Studio toolbox onto your form designer, then design a simple layout as shown below.

c# convert datatable to html table

I'm using Northwind database to play the demo.

Adding a datasource to your table in sql server.

add datasource to form designer

Entering your dataset name is AppData.

private void frmConvertDataTableToHtmlTable_Load(object sender, EventArgs e)
{
    // TODO: This line of code loads data into the 'appData.Customers' table. You can move, or remove it, as needed.
    this.customersTableAdapter.Fill(this.appData.Customers);
}

You can see the code is automatically added to the Form_Load event to help you get data from the customers table.

Creating an ExportDatatableToHtml method to help you convert data from DataTable to Html as shown below.

// c# export datatable to html
private string ExportDatatableToHtml(DataTable dt)
{
   // Start building HTML table
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.Append("<html >");
    stringBuilder.Append("<head>");
    stringBuilder.Append("<meta charset='utf-8'>");
    stringBuilder.Append("</head>");
    stringBuilder.Append(@"<link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css' integrity='sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk' crossorigin='anonymous'>");
    stringBuilder.Append("<script src='https://code.jquery.com/jquery-3.3.1.slim.min.js' integrity='sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo' crossorigin='anonymous'></script>");
    stringBuilder.Append("<script src='https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js' integrity='sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy' crossorigin='anonymous'></script>");
    stringBuilder.Append("<body>");
    stringBuilder.Append("<table class='table table-sm table-hover' style='margin: 20px;'>");
    // Add table header
    stringBuilder.Append("<thead>");
    stringBuilder.Append("<tr class='bg-primary' style='color: white; text-align: left;'>");
    foreach (DataColumn column in dt.Columns)
    {
        stringBuilder.Append("<th class='border border-secondary'>");
        stringBuilder.Append(column.ColumnName);
        stringBuilder.Append("</th>");
    }
    stringBuilder.Append("</tr>");
    stringBuilder.Append("</thead>");
    foreach (DataRow row in dt.Rows)
    {
        // Add table rows
        stringBuilder.Append("<tr>");
        foreach (DataColumn column in dt.Columns)
        {
            stringBuilder.Append("<td class='border border-secondary'>");
            stringBuilder.Append(row[column.ColumnName].ToString());
            stringBuilder.Append("</td>");
        }
        stringBuilder.Append("</tr>");
    }
    // Close HTML table
    stringBuilder.Append("</table>");
    stringBuilder.Append("</body>");
    stringBuilder.Append("</html>");
    // return html as a string
    var html = stringBuilder.ToString();
    return html;
}

You should use StringBuilder in loop to increase speed.

Finally, Add a click event handler to the Convert button allows you to export from datatable to html file.

// c# convert datatable to html
private void btnConvert_Click(object sender, EventArgs e)
{
    using (SaveFileDialog saveFileDialog = new SaveFileDialog() { Filter = "Html files|*.html" })
    {
        if (saveFileDialog.ShowDialog() == DialogResult.OK)
        {
           //c# write data to html file
            string html = ExportDatatableToHtml(this.appData.Customers.CopyToDataTable());
            System.IO.File.WriteAllText(saveFileDialog.FileName, html);
        }
    }
}

We create a StringBuilder to construct the HTML markup, then we iterate over the columns of the DataTable to build the table headers (<th>).

We iterate over the rows of the DataTable and then over the items within each row to build the table cells (<td>).

Finally, we close the HTML table and set the generated HTML as the content of a WebBrowser control.

You can place a WebBrowser control on your form to display the generated HTML. Make sure to call ExportDataTableToHtml() method with your DataTable whenever you need to display it.