public class ExcelTools
{
public static List<T> GetList<T>(string path,string sheetName = "Sheet1") where T : new()
{
var list = new List<T>();
IWorkbook workbook = new XSSFWorkbook(path);
var sheetAt = workbook.GetSheetIndex(sheetName);
var sheet = workbook.GetSheetAt(sheetAt == -1 ? 0 : sheetAt);
IRow cellNum = sheet.GetRow(0);
var propertys = typeof(T).GetProperties();
string value = null;
int num = cellNum.LastCellNum;
for (int i = 1; i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
var obj = new T();
for (int j = 0; j < num; j++)
{
var head = cellNum.Cells[j].StringCellValue;
var property = propertys.FirstOrDefault(e => e.Name == head);
value = row.GetCell(j)?.ToString().Trim();
if (property == null || string.IsNullOrEmpty(value))
{
continue;
}
var type = property.PropertyType;
if (type == typeof(string))
{
property.SetValue(obj, value, null);
}
else if (type == typeof(DateTime) || type == typeof(DateTime?))
{
var dt = row.GetCell(j).DateCellValue;
DateTime? pdt = Convert.ToDateTime(dt, CultureInfo.InvariantCulture);
property.SetValue(obj, pdt, null);
}
else if (type == typeof(bool) || type == typeof(bool?))
{
bool? pb;
if (value?.Trim() == "是" || value?.Trim() == "1")
{
pb = true;
}
else if(value?.Trim()=="否" || value?.Trim() == "0")
{
pb = false;
}
else
{
pb = row.GetCell(j).BooleanCellValue;
}
property.SetValue(obj, pb, null);
}
else if (type == typeof(int) || type == typeof(int?))
{
int? _int = (int)row.GetCell(j).NumericCellValue;
property.SetValue(obj, _int, null);
}
else if (type == typeof(long) || type == typeof(long?))
{
long? _long =(long)row.GetCell(j).NumericCellValue;
property.SetValue(obj, _long, null);
}
else if (type == typeof(double) || type == typeof(double?))
{
double? _long = row.GetCell(j).NumericCellValue;
property.SetValue(obj, _long, null);
}
else
{
property.SetValue(obj, null, null);
}
}
list.Add(obj);
}
return list;
}
}