NPOI 导入Excel
public static List GetExcelToList(string excelfileName) {
List list = new List();
ISheet sheet = null;
PropertyInfo propertyInfo = null;
int startRow = 0;
using (FileStream fs = new FileStream(excelfileName, FileMode.Open, FileAccess.Read))
{
workbook = new XSSFWorkbook(fs);
sheet= workbook.GetSheetAt(0);
if (sheet != null) {
IRow firstRow = sheet.GetRow(0);//第一行
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
startRow = sheet.FirstRowNum + 1;
for (int j = startRow; j < sheet.LastRowNum; j++)
{
IRow RowValue = sheet.GetRow(j);//数据行
T tmodel = new T();
Type type = tmodel.GetType();
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
try
{
ICell cell = firstRow.GetCell(i);
propertyInfo = type.GetProperty(cell.StringCellValue);
propertyInfo.SetValue(tmodel, RowValue.GetCell(i), null);
}
catch (Exception e)
{
new ArgumentOutOfRangeException("Excel导入失败", e);
}
}
list.Add(tmodel);
}
}
}
return list;
}