ClosedXML.Report uses an XLSX file as a template. You can design your report in Microsoft Excel (applying formatting, conditional formatting, pivot tables, etc.) and then use the XLTemplate class to inject .NET data into that template.
Workflow:
- Create a Template: Design an Excel file (
.xlsx) with your desired layout and formatting. - Load Template: Instantiate
XLTemplate with the path to your template file. - Add Data: Use
template.AddVariable(object) to pass .NET objects/data to the template. - Generate: Call
template.Generate() to process the data into the template. - Save: Use
template.SaveAs(path) to export the final report.
protected void Report()
{
const string outputFile = @".\Output\report.xlsx";
var template = new XLTemplate(@".\Templates\report.xlsx");
using (var db = new DbDemos())
{
// Load data from your source
var cust = db.customers.LoadWith(c => c.Orders).First();
// Map the data to the template
template.AddVariable(cust);
// Execute the generation logic
template.Generate();
}
// Save the resulting file
template.SaveAs(outputFile);
// Optional: Open the report
Process.Start(new ProcessStartInfo(outputFile) { UseShellExecute = true });
}