C# - Creating HTML reports
Solution 1
This seems like a great job for something like RazorEngine. You can define a template using Razor syntax, and then render out the content using the RazorEngine template service, e.g.:
@helper RenderItem(Item item) {
<tr>
<td>item.Name</td>
<td>item.Price</td>
</tr>
}
<html>
<head></head>
<body>
<table>
@foreach (Item item in Model.Items) {
@RenderItem(item)
}
</table>
</body>
</html>
Solution 2
You can save DataSet as XML
and then transform it by using XSLT
.
You can take a look at this samples:
- XSLT - Transformation
- Creating and Populating an HTML Template
- Using XSLT and .NET to Manipulate XML Files
Solution 3
I personally recommend generating HTML with Linq to Xml (using System.Xml.Linq)
You don't even have to use the strict XHTML schema's, but you'll get heap s of mileage out of Xml.Linq. Here is a snippet from my own code bases:
#region Table Dump Implementation
private static XNode Dump<T>(IEnumerable<T> items, IEnumerable<string> header, params Func<T, string>[] columns)
{
if (!items.Any())
return null;
var html = items.Aggregate(new XElement("table", new XAttribute("border", 1)),
(table, item) => {
table.Add(columns.Aggregate(new XElement("tr"),
(row, cell) => {
row.Add(new XElement("td", EvalColumn(cell, item)));
return row;
} ));
return table;
});
html.AddFirst(header.Aggregate(new XElement("tr"),
(row, caption) => { row.Add(new XElement("th", caption)); return row; }));
return html;
}
private static XNode EvalColumn<T>(Func<T, string> cell, T item)
{
var raw = cell(item);
try
{
var xml = XElement.Parse(raw);
return xml;
}
catch (XmlException)
{
return new XText(raw);
}
}
#endregion
#region Dot Diagrams
public void LinkDiagram(Digraph graph, string id)
{
if (!graph.AllNodes.Any())
return;
var img = Path.GetFileName(GenDiagramFile(graph, _directory, id));
_body.Add(
new XElement("a",
new XAttribute("href", img),
new XElement("h4", "Link naar: " + graph.name),
new XElement("img",
new XAttribute("border", 1),
new XAttribute("src", img),
new XAttribute("width", "40%"))));
}
Note that is it exceedingly easy to use inline HTML text as well (as long as it is valid XML), using a helper like so:
public void GenericAppend(string content)
{
if (!string.IsNullOrEmpty(content))
_body.Add(XElement.Parse(content));
}
Man1
Updated on August 17, 2022Comments
-
Man1 over 1 year
I have in my winform application 4 datasets that gets values from my database. Values like like how many products I have in my product table and information about categories. I was wondering how I can save the dataset informaiton in a html page. I want to create a html template so that I can present the information in nice way. How can I do that? Eny good guide that explains how to do that?