Convert DataTable to Html Page
Converts a DataTable into a full HTML page, including styling and an optional title.
This function builds a styled HTML document with embedded CSS, including alternating row colors, borders, and spacing. The table contents are generated using the ConvertDataTable2HtmlTable function.
VB
Public Function ConvertDataTable2HtmlPage(DataTable As Data.DataTable,
Optional title As String = "",
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()
' Set Style
htmlBuilder.AppendLine("<!DOCTYPE html>")
htmlBuilder.AppendLine("<html lang=""en"">")
htmlBuilder.AppendLine("<head>")
htmlBuilder.AppendLine(" <meta charset=""UTF-8"">")
htmlBuilder.AppendLine(" <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">")
htmlBuilder.AppendLine($" <title>{title}</title>")
htmlBuilder.AppendLine(" <style>")
htmlBuilder.AppendLine(" body {")
htmlBuilder.AppendLine($" font-family: {fontName}, Consolas;")
htmlBuilder.AppendLine(" margin: 20px;")
htmlBuilder.AppendLine(" }")
htmlBuilder.AppendLine(" table {")
htmlBuilder.AppendLine(" width: 100%;")
htmlBuilder.AppendLine(" border-collapse: collapse;")
htmlBuilder.AppendLine(" margin-top: 20px;")
htmlBuilder.AppendLine(" }")
htmlBuilder.AppendLine(" th, td {")
htmlBuilder.AppendLine(" border: 1px solid #ccc;")
htmlBuilder.AppendLine(" padding: 8px;")
htmlBuilder.AppendLine(" text-align: left;")
htmlBuilder.AppendLine(" }")
htmlBuilder.AppendLine(" th {")
htmlBuilder.AppendLine(" background-color: #f4f4f4;")
htmlBuilder.AppendLine(" }")
htmlBuilder.AppendLine(" tr:nth-child(even) {")
htmlBuilder.AppendLine(" background-color: #f9f9f9;")
htmlBuilder.AppendLine(" }")
htmlBuilder.AppendLine(" </style>")
htmlBuilder.AppendLine("</head>")
htmlBuilder.AppendLine("<body>")
' Title if any
If Not String.IsNullOrEmpty(title) Then
htmlBuilder.AppendLine($"<h1>{title}</h1>")
End If
' Build html table
htmlBuilder.AppendLine(ConvertDataTable2HtmlTable(DataTable, fontName))
htmlBuilder.AppendLine("</body>")
htmlBuilder.AppendLine("</html>")
Return htmlBuilder.ToString()
End Function