namespace CloudGaming.Core.Excel; /// /// excel 工具类 /// public static class ExcelUtil { #region Excel 映射 /// /// 获取字典集合 /// /// public static byte[] GetExcelByDict(List data) where TEntity : class, new() { if (data.Count == 0) { return []; } var dynamicExcelColumnList = new List(); var excelData = new List>(); var index = 0; // 将 data 组装为 excelData foreach (var item in data) { index++; var type = item.GetType(); var dict = new Dictionary(); foreach (var property in type.GetProperties()) { // 只有打了 excel 标记的字段才能导出 var excelAttribute = property.GetCustomAttribute(); if (excelAttribute is null) { continue; } var key = excelAttribute.Name; // 特殊处理一下如果 同时存在 Dict 和 Excel 标记,那么数据的值只能去读取 ToField 的值 var dictAttribute = property.GetCustomAttribute(); if (dictAttribute is not null) { var keyName = dictAttribute.ToField; if (string.IsNullOrWhiteSpace(keyName)) { throw new Exception("请设置 ToField 字段"); } else { var value = type.GetProperty(keyName)?.GetValue(item); dict[key] = value; } } else { var value = property.GetValue(item); dict[key] = value; } if (index == 1) { // 添加动态咧 配置 dynamicExcelColumnList.Add(new DynamicExcelColumn(key) { Name = excelAttribute.Name, // Index = excelAttribute.Index, Width = excelAttribute.Width, Format = excelAttribute.Format }); } } excelData.Add(dict); } // excel 配置 var config = new OpenXmlConfiguration { DynamicColumns = dynamicExcelColumnList.ToArray() }; using var stream = new MemoryStream(); stream.SaveAs(excelData, configuration: config); // 将 stream 转为 byte[] return stream.ToArray(); } #endregion }