使用反射技术实现的导入Excel文件到数据库的公共方法
来源:互联网 发布:淘宝上的万斯是真的吗 编辑:程序博客网 时间:2024/05/18 18:43
还是干脆、利索直接上代码最实惠。。。。
1. 定义接口类IImportService
public interface IImportService { /// <summary> /// 从XLSX导入信息到数据库 /// </summary> /// <param name="filePath">导入文件的全路径</param> /// <param name="propertyDic">Excel文档表头和数据库表字段的对应关系(例如Excel文件的"姓名"——》对应数据库的"Name")</param> List<T> ImportEntityListFromXlsx<T>(string filePath, Dictionary<string, string> propertyDic) where T : class,new(); }
2. 提供默认实现类 IImportService
public class ImportService : IImportService { private const string cmdText = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'"; public List<T> ImportEntityListFromXlsx<T>(string filePath, Dictionary<string, string> propertyDic) where T : class, new() { List<T> tempList = new List<T>(); using (OleDbConnection conn = new OleDbConnection(string.Format(cmdText, filePath))) { conn.Open(); DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); for (int i = 0; i < schemaTable.Rows.Count; i++) { string sheetName = schemaTable.Rows[i]["TABLE_NAME"].ToString().Trim(); //查询sheet中的数据 string strSql = "select * from [" + sheetName + "]"; OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn); DataSet ds = new DataSet(); da.Fill(ds); var dt = ds.Tables[0]; foreach (DataRow dr in dt.Rows) { T tempItem = (T)Activator.CreateInstance(typeof(T)); foreach (PropertyInfo pop in typeof(T).GetProperties()) { if (propertyDic.HasKey(pop.Name)) { if (!pop.PropertyType.IsGenericType) { pop.SetValue(tempItem, Convert.ChangeType(dr[propertyDic[pop.Name]], pop.PropertyType, null)); } else { //泛型Nullable<> Type genericTypeDefinition = pop.PropertyType.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { pop.SetValue(tempItem, string.IsNullOrEmpty(dr[propertyDic[pop.Name]].TryString()) ? null : Convert.ChangeType(dr[propertyDic[pop.Name]], Nullable.GetUnderlyingType(pop.PropertyType)), null); } } } } tempList.Add(tempItem); } } } return tempList; } }
3. 使用方法就不用多废话了吧。。。还是贴个图好了~_~
0 0
- 使用反射技术实现的导入Excel文件到数据库的公共方法
- excel文件到导入到数据库,date类型的处理
- POI导入Excel的公共方法
- 实现数据库到excel文件的下载
- 实现数据库到excel文件的下载
- 关于将EXCEL文件导入到MYSQL数据库的一些方法
- 关于将EXCEL文件导入到MYSQL数据库的一些方法
- 关于将EXCEL文件导入到MYSQL数据库的一些方法
- 把带有逗号的excel文件导入到sqlite数据库
- 导入excel格式的文件并写入到数据库中
- 基于struts2的导入excel文件到数据库操作
- 导入Excel电子表格数据到SQL Sever数据库的方法
- 导入Excel电子表格数据到SQL Sever数据库的方法
- excel数据导入到oracle数据库的方法总结
- 利用java反射机制导出Excel的公共方法以及使用的方法
- jsp中将数据库中的数据导入到excel的实现
- jsp中将数据库中的数据导入到excel的实现
- jsp中将数据库中的数据导入到excel的实现
- UIBarbuttonItem
- TensorFlow实现CNN
- rsync错误日志
- Android中获取网络天气数据
- 永不锁屏
- 使用反射技术实现的导入Excel文件到数据库的公共方法
- 配置在线加载依赖库(dependences),gradle同步出现manifest合并失败:Manifest merger failed with multiple errors, see logs
- python中导入其他目录下的模块
- rsync.conf详解
- bootstrap modal对话框
- linux yum命令详解
- USB协通讯议--深入理解
- 服务器搭建
- ios 别踩白块...