// Services/CsvExportService.cs using System.IO; using System.Text; using System.Collections.Generic; using System.Reflection; using System.Linq;
publicclassCsvExportService : ICsvExportService { public Stream ExportToCsv<T>(IEnumerable<T> reportData) { var memoryStream = new MemoryStream(); var streamWriter = new StreamWriter(memoryStream, Encoding.UTF8);
if (reportData != null && reportData.Any()) { // 透過反射取得 T 的所有公開屬性 var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
// Controllers/ReportController.cs using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; // 需要引入這個命名空間 using Microsoft.EntityFrameworkCore; // 需要引入這個命名空間 using YourAppName.Services; using YourAppName.Data; // 引入 DbContext 命名空間 using YourAppName.Models; // 引入 Student 命名空間
優點: 它的主要優點是提升程式碼的可讀性與可維護性。任何閱讀你程式碼的人,一眼就能知道這個 API 端點預計回傳的是 CSV 格式。此外,如果你的專案使用了 Swagger/OpenAPI 等 API 文件生成工具,這些工具會自動讀取 [Produces] 屬性,並將其包含在 API 文件中,讓你的文件更完整、更精確,對於 API 的使用者來說非常方便。
四、設定依賴注入
在 Program.cs 裡註冊你的 DbContext 和 ICsvExportService。
在 Program.cs 裡:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
var builder = WebApplication.CreateBuilder(args);
// Add services to the container. builder.Services.AddControllers();