51 lines
1.7 KiB
C#
51 lines
1.7 KiB
C#
using System.Reflection;
|
|
using OfficeOpenXml;
|
|
|
|
namespace Dlhis.ExcelHelper;
|
|
|
|
public static class ExcelExtensions
|
|
{
|
|
public static async Task<byte[]> ToExcelBytesAsync<T>(this List<T> data)
|
|
{
|
|
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
|
|
|
|
var type = typeof(T);
|
|
var sheetName = type.GetCustomAttribute<ExcelAttribute>()?.Description ?? type.Name;
|
|
var excelHeaderNames = type.GetProperties().Where(x => x.IsDefined(typeof(ExcelAttribute))).ToList();
|
|
|
|
using var package = new ExcelPackage();
|
|
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(sheetName);
|
|
|
|
// 写入表头
|
|
for (int i = 0; i < excelHeaderNames.Count; i++)
|
|
{
|
|
var cell = worksheet.Cells[1, i + 1];
|
|
worksheet.Column(i + 1).BestFit = true;
|
|
cell.Style.Font.Bold = true;
|
|
cell.Value = excelHeaderNames[i].GetCustomAttribute<ExcelAttribute>()!.Description;
|
|
}
|
|
|
|
int row = 2;
|
|
foreach (var item in data)
|
|
{
|
|
for (int col = 0; col < excelHeaderNames.Count; col++)
|
|
{
|
|
var column = excelHeaderNames[col];
|
|
var value = column.GetValue(item);
|
|
|
|
var cell = worksheet.Cells[row, col + 1];
|
|
var format = column.GetCustomAttribute<ExcelAttribute>()!.Format;
|
|
cell.Value = value;
|
|
if (!string.IsNullOrEmpty(format))
|
|
{
|
|
cell.Style.Numberformat.Format = format;
|
|
}
|
|
}
|
|
|
|
row++;
|
|
}
|
|
|
|
worksheet.Cells.AutoFitColumns();
|
|
return await package.GetAsByteArrayAsync();
|
|
}
|
|
} |