```csharp public class ExportData { [Column("姓名")] public string Name { get; set; }

[Column("年龄")] public int Age { get; set; } }

public IActionResult Export() { var dataList = new List<ExportData> { new ExportData { Name = "张三", Age = 20 }, new ExportData { Name = "李四", Age = 25 } };

byte[] fileBytes;

using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("Sheet1");

// 获取ExportData类中所有带有Column特性的属性 var properties = typeof(ExportData).GetProperties() .Where(p => Attribute.IsDefined(p, typeof(ColumnAttribute)));

// 设置列名 foreach (var property in properties) { var columnAttribute = property.GetCustomAttribute<ColumnAttribute>(); var displayName = columnAttribute.DisplayName; var order = columnAttribute.Order;

worksheet.Cells[1, order].Value = displayName; }

// 填充数据 for (int i = 0; i < dataList.Count; i++) { var data = dataList[i]; var rowIndex = i + 2;

foreach (var property in properties) { var order = property.GetCustomAttribute<ColumnAttribute>().Order; var value = property.GetValue(data);

worksheet.Cells[rowIndex, order].Value = value; } }

fileBytes = package.GetAsByteArray(); }

return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "export.xlsx"); } ```


原文地址: https://www.cveoy.top/t/topic/p9Dl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录