How to build a reusable Excel export service in ASP.NET Core
This article will teach you how to export any list into Excel in C# using the ClosedXML library. Steps to complete Create the data model with dummy data that we'll export into Excel. Create ExportExcel interface methods that accept any type of List (using IEnumerable<T> ) and a Dictionary List and export a byte array. Create extension methods and convert the provided data into rows and columns (using DataTable ). Create a service class that implements the interface methods and export the data table into a Memory Stream (byte array) using ClosedXML . Create one API endpoint that exports data in memory into Excel. Create another endpoint that exports incoming (custom) request data into Excel. Wire up dependencies. Project structure ├── Program.cs ← Project startup & dependency injection │ ├── controllers / │ └── ExportToExcelController.cs ← API entry point ├── services / │ ├── IExportToExcelService.cs ← Export Excel interface │ └── ExportToExcelService.cs ← Export Excel concrete class │ ├── models / │ ├── Car.cs ← Car class definition & dummy data │ ├── ExcelResponse.cs ← Wrapper class for excel file name and data │ └── ExportExcelRequest.cs ← Request class for that accepts any kind of list that will be exported │ └── extensions / └── IEnumerableExtensions.cs ← Extension methods for List<T> and List<Dictionary> 1️⃣ Data model I've created the dummy data model to demonstrate the dynamic implementation. public enum FuelType { Petrol, Diesel, Electric, Hybrid } public class Car { public Guid Id { get; set; } public string Name { get; set; } public string Manufacturer { get; set; } public int YearProduced { get; set; } public string Color { get; set; } public FuelType FuelType { get; set; } public int HorsePower { get; set; } public int NumberOfDoors { get; set; } public bool AutomaticTransmission { get; set; } public double AverageFuelConsumption { get; set; } public int MaxSpeed { get; set; } public decimal Price { get; set; } public static List<Car> GetCars() { ... } }