导出成List
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ExcelColumnAttribute : Attribute
{
public ExcelColumnAttribute(int columnIndex)
{
ColumnIndex = columnIndex;
}
public ExcelColumnAttribute(string columnName)
{
ColumnName = columnName;
}
public int ColumnIndex { get; }
public string? ColumnName { get; }
}
public static List<T> ExcelExportList<T>(string filePath, int sheetIndex)
{
List<T> dataList = new List<T>();
Workbook workbook = new Workbook(filePath);
Worksheet worksheet = workbook.Worksheets[sheetIndex];
PropertyInfo[] properties = typeof(T).GetProperties();
for (int rowIndex = 1; rowIndex <= worksheet.Cells.MaxDataRow; rowIndex++)
{
T myData = (T)Activator.CreateInstance(typeof(T))!;
foreach (var property in properties)
{
var attributes = property.GetCustomAttributes(typeof(ExcelColumnAttribute), false);
if (attributes is [ExcelColumnAttribute])
{
var at = ((ExcelColumnAttribute)attributes[0]);
if (string.IsNullOrEmpty(at.ColumnName)||string.IsNullOrWhiteSpace(at.ColumnName))
{
int columnIndex = at.ColumnIndex;
string value = worksheet.Cells[rowIndex, columnIndex].StringValue;
property.SetValue(myData, Convert.ChangeType(value, property.PropertyType), null);
}
else
{
string columnName = at.ColumnName;
string value = worksheet.Cells[$"{columnName}{rowIndex+1}"].StringValue;
property.SetValue(myData, Convert.ChangeType(value, property.PropertyType), null);
}
}
}
dataList.Add(myData);
}
return dataList;
}