1.自定义特性

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class PropertyDescriptionAttribute : Attribute
{
private bool _allownullorempty = true;
public PropertyDescriptionAttribute() { }
/// <summary>
/// 是否允许为null或空值
/// </summary>
public bool AllowNullOrEmpty
{
get
{
return this._allownullorempty;
}
set
{
this._allownullorempty = value;
}
}
}

2.定义类(假设是用户信息)

public class UploadUserModel
{
[PropertyDescription(AllowNullOrEmpty = false)]
public string Name { get; set; }
[PropertyDescription(AllowNullOrEmpty = false)]
public string Phone { get; set; }
}

自定义特定来标识这两个信息不能为空

3.实现

/// <summary>
/// PROPERTY_NAME数组:值与excel列一一对应
/// </summary>
private readonly string[] PROPERTY_NAME = { "Name", "Phone" }; private List<UploadUserModel> ExcelToList(HttpPostedFile excelFile)
{
IWorkbook workbook = null;
ISheet sheet = null;
int colCount = ;
List<UploadUserModel> users = new List<UploadUserModel>();
if (excelFile.FileName.IndexOf(".xlsx") > )
{
workbook = new XSSFWorkbook(excelFile.InputStream);
}
else if (excelFile.FileName.IndexOf(".xls") > )
{
workbook = new HSSFWorkbook(excelFile.InputStream);
}
if (workbook != null)
{
sheet = workbook.GetSheetAt();
if (sheet != null && sheet.LastRowNum > )
{
colCount = sheet.GetRow().LastCellNum;//获取列数
//从第二行开始解析
for (int rowIndex = ; rowIndex <= sheet.LastRowNum; rowIndex++)
{
var curRow = sheet.GetRow(rowIndex);//获取当前行
UploadUserModel user = new UploadUserModel();
Type cType = user.GetType();
//解析列
for (int colIndex = ; colIndex < colCount; colIndex++)
{
var curCell = curRow.GetCell(colIndex);
if (curCell != null)
{
curCell.SetCellType(CellType.String);//把单元格设置成String类型,统一取值方式
}
//定义PROPERTY_NAME避免if判断
PropertyInfo propertyInfo = cType.GetProperty(PROPERTY_NAME[colIndex]);
//获取自定义特性
object[] customAttrs = propertyInfo.GetCustomAttributes(typeof(PropertyDescriptionAttribute), true);
if (customAttrs.Length > )
{
PropertyDescriptionAttribute attr = customAttrs[] as PropertyDescriptionAttribute;
if (!attr.AllowNullOrEmpty)//属性值不能为空
{
if (curCell == null)
{
throw new Exception("第" + (rowIndex + ).ToString() + "行有未填项,请填写后重新上传。");
}
else if (string.IsNullOrEmpty(curCell.StringCellValue))
{
throw new Exception("第" + (rowIndex + ).ToString() + "行有未填项,请填写后重新上传。");
}
}
object cellValue = null;
if (curCell == null)
{
cellValue = "";
}
else
{
cellValue = curCell.StringCellValue;
}
if (!propertyInfo.PropertyType.IsGenericType)
{
//非泛型
propertyInfo.SetValue(user, curCell == null ? null : Convert.ChangeType(cellValue, propertyInfo.PropertyType), null);
}
else
{
//泛型Nullable<>
Type genericTypeDefinition = propertyInfo.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
propertyInfo.SetValue(user, curCell == null ? null : Convert.ChangeType(cellValue, Nullable.GetUnderlyingType(propertyInfo.PropertyType)), null);
}
}
}
}
users.Add(user);
}
}
}
else
{
throw new Exception("Excel解析异常");
}
foreach (var item in users)
{
if (!checkPhoneGS(item.Phone))
{
throw new Exception("手机号格式不正确:"+ item.Phone);
}
}
return users;
}

不要看着麻烦,核心代码很简单。用反射和定义PROPERTY_NAME数组是为了代码重用。最后那段泛型、非泛型判断可以删除,估计一般用不到

最新文章

  1. 将HTML5封装成android应用APK文件的几种方法
  2. nginx 配置优化(简单)
  3. [转]TextArea设置MaxLength属性最大输入值的js代码
  4. 5.8---像素设定(CC150)
  5. 转:C++语言的15个晦涩特性
  6. delphi TSaveDialog
  7. 暴力求解——POJ 1321 棋盘问题
  8. android 焦点问题
  9. xilinx和altera复位电平
  10. [HEOI2015]小Z的房间
  11. GsonFormat插件
  12. Django JSON,AJAX
  13. 团队的Kick off
  14. (转)MySQL join语法解析与性能分析
  15. 【noip 2015】普及组
  16. hdu 1237 简单计算器 (表达式求值)【stack】
  17. VirtualBox运行出现“0x00000000指令引用的0x00000000内存。该内存不能为written” ,错误解决
  18. netty随笔
  19. [UE4]链接多个字符串Make Literal String
  20. Java 社区平台 - Sym 1.7.0 发布

热门文章

  1. HTML&CSS精选笔记_CSS高级技巧
  2. Messages: No result defined for action cn.itcast.oa.test.TestAction and result SUCCESS
  3. laravel 社会化(联合)登录扩展包(QQ、微信、微博等)
  4. 基于Cocos2d-x学习OpenGL ES 2.0系列——你的第一个三角形(1)
  5. 《C++ Primer Plus》第14章 C++中的代码重用 学习笔记
  6. HTTP/2笔记之帧
  7. LeetCode——Add and Search Word - Data structure design
  8. outline的兼容性及使用限制
  9. Android MemInfo 各项的意义(转)
  10. ipmi监控主机