因为前一段时间公司做项目的时候,用到了Excel导入和导出,然后自己找了个插件Epplus进行操作,自己将当时的一些代码抽离出来写了一个帮助类。

因为帮助类是在Epplus基础之上写的,项目需要引用Epplus.dll。自己基础不是很扎实,有问题的地方欢迎指导。

1.用法,默认excel第一列是头部信息。

    public class UserInfo : XlsRow
{
public int id { get; set; }
public string username { get; set; }
public string address { get; set; }
public int userage { get; set; }
public DateTime birthday { get; set; }
public decimal total { get; set; }
public string grade { get; set; }
}   static void Main(string[] args)
{
string filePath = "E:\\ExcelConvertEntity\\datatest.xlsx"; //转换address列的时候在所有地址钱添加“上海市”三个字
ECEntityCOM<UserInfo>.ForMember(e => e.address, e => "上海市:" + e); //excel列name对应实体username进行映射
ECEntityCOM<UserInfo>.ForMember("name", e => e.username); //列名age映射到实体userage属性,映射过程中给所有age加5
ECEntityCOM<UserInfo>.ForMember("age", e => e.userage, e => Convert.ToInt32(e) + ); //读取excel转换成List<UserInfo>
List<UserInfo> list = ECEntityCOM<UserInfo>.LoadFromExcel(filePath); Console.WriteLine("ok");
Console.ReadLine();
}

a.实体需要继承我的自定义实体XlsRow,这个实体会记录转换过程出错信息,转换这一行的时候,是否出现过错误,具体是那一列出错的。转换出错单元格内内容是什么,还有错误信息。

  public class XlsRow
{
/// <summary>
/// 错误信息
/// </summary>
public List<string> ErrMessage { get; set; } /// <summary>
/// 错误列名
/// </summary>
public List<string> ErrColumn { get; set; } /// <summary>
/// 错误内容
/// </summary>
public List<string> ErrValue { get; set; } /// <summary>
/// 是否转换出错(false:未出错,true:出错)
/// </summary>
public bool IsErr { get; set; }
}

然后转换过程中提供了几个方法,用来更好的自定义转换形式。

b.转换过程中,某一列统一进行某些处理操作,最后把处理后的信息存进实体列名里。

        //转换address列的时候在所有地址钱添加“上海市”三个字
ECEntityCOM<UserInfo>.ForMember(e => e.address, e => "上海市:" + e);

c.实体名跟excel列头部名称不一致,可以自定义映射。

       //excel列name对应实体username进行映射
ECEntityCOM<UserInfo>.ForMember("name", e => e.username);

d.自定义映射对excel单元格信息进行处理。

           //列名age映射到实体userage属性,映射过程中给所有age加5
ECEntityCOM<UserInfo>.ForMember("age", e => e.userage, e => Convert.ToInt32(e) + );

帮助类:

    #region 需要用到的实体

    public class XlsEntity
{
/// <summary>
/// 实体名称
/// </summary>
public string EntityName { get; set; } /// <summary>
/// 列名称
/// </summary>
public string ColumnName { get; set; } /// <summary>
/// 列下标
/// </summary>
public int ColumnIndex { get; set; } /// <summary>
/// 转换方法
/// </summary>
public Func<string, object> ConvertFunc { get; set; }
} public class XlsRow
{
/// <summary>
/// 错误信息
/// </summary>
public List<string> ErrMessage { get; set; } /// <summary>
/// 错误列名
/// </summary>
public List<string> ErrColumn { get; set; } /// <summary>
/// 错误内容
/// </summary>
public List<string> ErrValue { get; set; } /// <summary>
/// 是否转换出错(false:未出错,true:出错)
/// </summary>
public bool IsErr { get; set; }
} #endregion public class ECEntityCOM<T> where T : XlsRow, new()
{ private static List<XlsEntity> xlsHeader = new List<XlsEntity>(); #region 初始化转换形式 public static void ForMember(Expression<Func<T, object>> entityExpression, Func<string, object> func)
{
XlsEntity xlsEntity = new XlsEntity();
xlsEntity.EntityName = GetPropertyName(entityExpression);
xlsEntity.ColumnName = xlsEntity.EntityName;
xlsEntity.ConvertFunc = func;
xlsHeader.Add(xlsEntity);
} public static void ForMember(string columnName, Expression<Func<T, object>> entityExpression)
{
XlsEntity xlsEntity = new XlsEntity();
xlsEntity.ColumnName = columnName;
xlsEntity.EntityName = GetPropertyName(entityExpression);
xlsHeader.Add(xlsEntity);
} public static void ForMember(string columnName, string entityName)
{
XlsEntity xlsEntity = new XlsEntity();
xlsEntity.ColumnName = columnName;
xlsEntity.EntityName = entityName;
xlsHeader.Add(xlsEntity);
} public static void ForMember(string columnName, string entityName, Func<string, object> func)
{
XlsEntity xlsEntity = new XlsEntity();
xlsEntity.ColumnName = columnName;
xlsEntity.EntityName = entityName;
xlsEntity.ConvertFunc = func;
xlsHeader.Add(xlsEntity);
} public static void ForMember(string columnName, Expression<Func<T, object>> entityExpression, Func<string, object> func)
{
XlsEntity xlsEntity = new XlsEntity();
xlsEntity.ColumnName = columnName;
xlsEntity.EntityName = GetPropertyName(entityExpression);
xlsEntity.ConvertFunc = func;
xlsHeader.Add(xlsEntity);
} #endregion #region 从Excel中加载数据(泛型) public static List<T> LoadFromExcel(string filePath)
{
FileInfo existingFile = new FileInfo(filePath);
List<T> resultList = new List<T>(); using (ExcelPackage package = new ExcelPackage(existingFile))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[]; int colStart = worksheet.Dimension.Start.Column;
int colEnd = worksheet.Dimension.End.Column;
int rowStart = worksheet.Dimension.Start.Row;
int rowEnd = worksheet.Dimension.End.Row; PropertyInfo[] propertyInfoList = typeof(T).GetProperties();
XlsEntity xlsEntity; #region 将实体和excel列标题进行对应绑定,添加到集合中 for (int i = colStart; i <= colEnd; i++)
{
string columnName = worksheet.Cells[rowStart, i].Value.ToString(); xlsEntity = xlsHeader.FirstOrDefault(e => e.ColumnName == columnName); for (int j = ; j < propertyInfoList.Length; j++)
{ if (xlsEntity != null && xlsEntity.ColumnName == columnName)
{
xlsEntity.ColumnIndex = i;
xlsHeader.Add(xlsEntity);
}
else if (propertyInfoList[j].Name == columnName)
{
xlsEntity = new XlsEntity();
xlsEntity.ColumnName = columnName;
xlsEntity.EntityName = propertyInfoList[j].Name;
xlsEntity.ColumnIndex = i;
xlsHeader.Add(xlsEntity);
break;
}
}
} #endregion #region 根据对应的实体名列名的对应绑定就行值的绑定 for (int row = rowStart + ; row < rowEnd; row++)
{
T result = new T();
foreach (PropertyInfo p in propertyInfoList)
{
var xlsRow = xlsHeader.FirstOrDefault(e=> e.EntityName == p.Name);
if (xlsRow == null) continue; ExcelRange cell = worksheet.Cells[row, xlsRow.ColumnIndex];
if (cell.Value == null) continue; try
{
if (xlsRow.ConvertFunc != null)
{
object entityValue = xlsRow.ConvertFunc(cell.Value.ToString());
p.SetValue(result, entityValue);
}
else
{
cellBindValue(result, p, cell);
}
}
catch (Exception ex)
{
if (result.ErrColumn == null) result.ErrColumn = new List<string>();
if (result.ErrMessage == null) result.ErrMessage = new List<string>();
if (result.ErrValue == null) result.ErrValue = new List<string>();
result.ErrColumn.Add(p.Name);
result.ErrMessage.Add(ex.Message);
result.ErrValue.Add(cell.Value.ToString());
result.IsErr = true;
}
}
resultList.Add(result);
} #endregion
}
return resultList;
} #endregion #region 给实体绑定值 private static void cellBindValue(T result, PropertyInfo p, ExcelRange cell)
{
switch (p.PropertyType.Name.ToLower())
{
case "string":
p.SetValue(result, cell.GetValue<String>());
break;
case "int16":
p.SetValue(result, cell.GetValue<Int16>());
break;
case "int32":
p.SetValue(result, cell.GetValue<Int32>());
break;
case "int64":
p.SetValue(result, cell.GetValue<Int64>());
break;
case "decimal":
p.SetValue(result, cell.GetValue<Decimal>());
break;
case "double":
p.SetValue(result, cell.GetValue<Double>());
break;
case "datetime":
p.SetValue(result, cell.GetValue<DateTime>());
break;
case "boolean":
p.SetValue(result, cell.GetValue<Boolean>());
break;
case "byte":
p.SetValue(result, cell.GetValue<Byte>());
break;
case "char":
p.SetValue(result, cell.GetValue<Char>());
break;
case "single":
p.SetValue(result, cell.GetValue<Single>());
break;
default:
p.SetValue(result, cell.Value);
break;
}
} #endregion #region 获取Lambda的属性名称 private static string GetPropertyName(Expression<Func<T, object>> expression)
{
Expression expressionToCheck = expression;
bool done = false;
while (!done)
{
switch (expressionToCheck.NodeType)
{
case ExpressionType.Convert:
expressionToCheck = ((UnaryExpression)expressionToCheck).Operand;
break;
case ExpressionType.Lambda:
expressionToCheck = ((LambdaExpression)expressionToCheck).Body;
break;
case ExpressionType.MemberAccess:
var memberExpression = ((MemberExpression)expressionToCheck);
string propertyName = memberExpression.Member.Name;
return propertyName;
default:
done = true;
break;
}
}
return "";
} #endregion }

补充一个例子

http://files.cnblogs.com/ariklee/ExcelConvertEntity.rar

Epplus下的一个将Excel转换成List的范型帮助类的更多相关文章

  1. Linux下将UTF8编码批量转换成GB2312编码的方法

    Linux下将UTF8编码批量转换成GB2312编码的方法 在sqlplus中导入UTF8编码的sql脚本就会出现乱码错误,这时就需要将UTF8编码转换成GB2312编码,下面为大家介绍下在Linux ...

  2. 字符串A转换到字符串B,只能一次一次转换,每次转换只能把字符串A中的一个字符全部转换成另一个字符,是否能够转换成功

    public class DemoTest { public static void main(String[] args) { System.)); } /** * 有一个字符串A 有一个字符串B ...

  3. 使用 js 实现一个中文自动转换成拼音的工具库

    使用 js 实现一个中文自动转换成拼音的工具库 中文 => zhong-wen 应用场景 SEO 友好, URL 自动转换 blogs 发布文章,自动化部署,自动生成 url 的 path (时 ...

  4. Mac地址转换成long长整型

    Mac地址转换成long长整型 using System;using System.Collections.Generic;using System.IO;using System.Text;usin ...

  5. Mac地址转换成long长整型 2

    数据之间的转换可以使用   System.Convert Mac地址转换成long长整型 /// <summary> /// 解析长整形的数据使其转换为macID /// </sum ...

  6. 利用NPOI将EXCEL转换成HTML的C#实现

    领导说想做一个网页打印功能,而且模板可以自定义,我考虑了三个方案,一是打印插件,二是在线 html 编辑器,三是 excel 模板,领导建议用的是打印插件的形式,我研究了一下,一个是需要下载安装,二个 ...

  7. C# Excel转换成Json工具(含源码)

    可执行版本下载:https://github.com/neil3d/excel2json/releases 完整项目源代码下载:https://github.com/neil3d/excel2json ...

  8. Java中Office(word/ppt/excel)转换成HTML实现

    运行条件:JDK + jacob.jar + jacob.dll 1) 把jacob.dll在 JAVA_HOME\bin\ 和 JAVA_HOME\jre\bin\ 以及C:\WINDOWS\sys ...

  9. 多页Excel转换成PDF时如何保存为单独文件

    通过ABBYY PDF Transformer+图文识别软件,使用PDF-XChange打印机将多页Excel工作簿转换成PDF文档(相关文章请参考ABBYY PDF Transformer+从MS ...

随机推荐

  1. Bokeh 学习

    这段时间由于在做K-means对文本进行处理,需要进行绘图,实验室编程大哥向我介绍了Bokeh来进行绘图,一直是根据自己的需求来进行对其探索,今儿个看到一篇博文,对Bokeh进行了详细的解说,做个笔记 ...

  2. 在文本框输入数据后,因为有历史记录,鼠标点或者敲回车这个历史记录时,请问会触发什么JS事件

    非ie触发 oninput事件,ie触发>onpropertychange事件 jquery写法 $("#input").bind("input propertyc ...

  3. PHP设计模式——责任链模式

    <?php /** * 责任链模式 * 组织一个对象链处理一个请求,每个处理对象知道自己能处理哪些请求,并把自己不能处理的请求交下一个处理对象 * * 适用场景: * 1.有多个对象可以处理同一 ...

  4. 【题解】洛谷P2426删数

    链接 https://www.luogu.org/problemnew/show/P2426 念念碎 第一次接触到区间DP(瑟瑟发抖) 所以象征性地看了一下题解 这好像是一道比较基础的区间DP吧 但是 ...

  5. Anaconda的使用—Spyder常用快捷键

    Ctrl + 1: 注释/反注释 Ctrl + 4/5: 块注释/块反注释 Ctrl + L: 跳转到行号 Tab/Shift + Tab: 代码缩进/反缩进 Ctrl +I:显示帮助

  6. Java跨系统调用接口(POST)

    package com.bing.util; import com.bing.constant.ResultModel; import com.bing.model.Company; import c ...

  7. PTA 最多删除3个字符(DP) - 30分

    给定一个全部由小写英文字母组成的字符串,允许你至多删掉其中 3 个字符,结果可能有多少种不同的字符串? 输入格式: 输入在一行中给出全部由小写英文字母组成的.长度在区间 [4, 1] 内的字符串. 输 ...

  8. Lucas定理及应用

    额,前两天刚讲了数据结构,今天我来讲讲组合数学中的一种奇妙优化——Lucas 先看这样一个东西 没学过lucas的肯定会说:还不简单?处理逆元,边乘边膜呗 是,可以,但注意一下数据范围 你算这一次,你 ...

  9. poj_3256_Cow Picnic

    The cows are having a picnic! Each of Farmer John's K (1 ≤ K ≤ 100) cows is grazing in one of N (1 ≤ ...

  10. SAP销售订单屏幕字段控制隐藏,必输等

    1.T-CODE:shd0 创建变式  , 点击确认按钮后,SAP进入下一个屏幕,然后重复上面的操作,直到所有屏幕已完成设置. 如果后续屏幕不需要设置,可点击“退出并保存”按钮.保存后,进入下图所示页 ...