Convert DataTable to Html Table
Converts a DataTable to an HTML table string.
The function builds a complete HTML table including the <tbody> and sections. No additional CSS styling is applied, and all values are inserted as raw text (not HTML-encoded).
VB
Public Function ConvertDataTable2HtmlTable(DataTable As Data.DataTable,
Optional fontName As String = "Calibri") As String
' No data
If DataTable Is Nothing OrElse DataTable.Rows.Count = 0 Then
Return $"<html><body><p style='font-family:{fontName};'>No data available</p></body></html>"
End If
' Build HTML
Dim htmlBuilder As New Text.StringBuilder()
' Open table
htmlBuilder.AppendLine("<table>")
' Column headers
htmlBuilder.AppendLine("<thead>")
htmlBuilder.AppendLine("<tr>")
For Each col As Data.DataColumn In DataTable.Columns
htmlBuilder.AppendLine($"<th>{col.ColumnName}</th>")
Next
htmlBuilder.AppendLine("</tr>")
htmlBuilder.AppendLine("</thead>")
' Table content
htmlBuilder.AppendLine("<tbody>")
For Each row As Data.DataRow In DataTable.Rows
htmlBuilder.AppendLine("<tr>")
For Each col As Data.DataColumn In DataTable.Columns
htmlBuilder.AppendLine($"<td>{row(col)}</td>")
Next
htmlBuilder.AppendLine("</tr>")
Next
htmlBuilder.AppendLine("</tbody>")
htmlBuilder.AppendLine("</table>")
Return htmlBuilder.ToString()
End Function