今日已更新 80 条资讯 | 累计 20052 条内容
关于我们

How to build a reusable Excel export service in ASP.NET Core

Mirza Leka 2026年05月30日 17:36 4 次阅读 来源:Dev.to

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() { ... } }

本文内容来源于互联网,版权归原作者所有
查看原文