using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace ConsoleApp2.test1 { public class Class10 { public void test1() { var dt = CSVFileHelper.OpenCSV(@"1.csv"); dt.Columns["联系人姓名"].ColumnName = "Name"; dt.Columns["备注"].ColumnName = "Remark"; var list = dt.DataTableToEntities<Crm_Cm_ContactInfo2>(); Console.WriteLine(dt.Rows.Count); Console.WriteLine(JsonConvert.SerializeObject(list)); } } public class Crm_Cm_ContactInfo2 { public string Name { get; set; } public string Remark { get; set; } } public class CSVFileHelper { /// <summary> /// 将DataTable中数据写入到CSV文件中 /// </summary> /// <param name="dt">提供保存数据的DataTable</param> /// <param name="fileName">CSV的文件路径</param> public static void SaveCSV(DataTable dt, string fullPath) { FileInfo fi = new FileInfo(fullPath); if (!fi.Directory.Exists) { fi.Directory.Create(); } FileStream fs = new FileStream(fullPath, System.IO.FileMode.Create, System.IO.FileAccess.Write); //StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default); StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8); string data = ""; //写出列名称 for (int i = 0; i < dt.Columns.Count; i++) { data += dt.Columns[i].ColumnName.ToString(); if (i < dt.Columns.Count - 1) { data += ","; } } sw.WriteLine(data); //写出各行数据 for (int i = 0; i < dt.Rows.Count; i++) { data = ""; for (int j = 0; j < dt.Columns.Count; j++) { string str = dt.Rows[i][j].ToString(); str = str.Replace(""", """");//替换英文冒号 英文冒号需要换成两个冒号 if (str.Contains(',') || str.Contains('"') || str.Contains(' ') || str.Contains(' ')) //含逗号 冒号 换行符的需要放到引号中 { str = string.Format(""{0}"", str); } data += str; if (j < dt.Columns.Count - 1) { data += ","; } } sw.WriteLine(data); } sw.Close(); fs.Close(); } /// <summary> /// 将CSV文件的数据读取到DataTable中 /// </summary> /// <param name="fileName">CSV文件路径</param> /// <returns>返回读取了CSV数据的DataTable</returns> public static DataTable OpenCSV(string filePath) { Encoding encoding = Encoding.Default; //Encoding.ASCII;//Common.GetType(filePath) DataTable dt = new DataTable(); FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); //StreamReader sr = new StreamReader(fs, Encoding.UTF8); StreamReader sr = new StreamReader(fs, encoding); //string fileContent = sr.ReadToEnd(); //encoding = sr.CurrentEncoding; //记录每次读取的一行记录 string strLine = ""; //记录每行记录中的各字段内容 string[] aryLine = null; string[] tableHead = null; //标示列数 int columnCount = 0; //标示是否是读取的第一行 bool IsFirst = true; //逐行读取CSV中的数据 while ((strLine = sr.ReadLine()) != null) { //strLine = Common.ConvertStringUTF8(strLine, encoding); //strLine = Common.ConvertStringUTF8(strLine); if (IsFirst == true) { tableHead = strLine.Split(','); IsFirst = false; columnCount = tableHead.Length; //创建列 for (int i = 0; i < columnCount; i++) { DataColumn dc = new DataColumn(tableHead[i]); dt.Columns.Add(dc); } } else { aryLine = strLine.Split(','); DataRow dr = dt.NewRow(); for (int j = 0; j < columnCount; j++) { dr[j] = aryLine[j]; } dt.Rows.Add(dr); } } if (aryLine != null && aryLine.Length > 0) { dt.DefaultView.Sort = tableHead[0] + " " + "asc"; } sr.Close(); fs.Close(); return dt; } } /// <summary> /// 反射类 /// </summary> public static class MyReflection { /// <summary> /// DataTable 转换为 对象List /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dt"></param> /// <returns></returns> public static List<T> DataTableToEntities<T>(this DataTable dt) where T : class, new() { if (null == dt || dt.Rows.Count == 0) { return null; } List<T> entities = new List<T>(); foreach (DataRow row in dt.Rows) { PropertyInfo[] pArray = typeof(T).GetProperties(); T entity = new T(); Array.ForEach<PropertyInfo>(pArray, p => { object cellvalue = row[p.Name]; if (cellvalue != DBNull.Value) { //经过了几个版本的迭代,最后一个为最新的,摘自网上,已附原文地址 //4、原地址:https://blog.csdn.net/Simon1003/article/details/80839744 if (!p.PropertyType.IsGenericType) { p.SetValue(entity, Convert.ChangeType(cellvalue, p.PropertyType), null); } else { Type genericTypeDefinition = p.PropertyType.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { p.SetValue(entity, Convert.ChangeType(cellvalue, Nullable.GetUnderlyingType(p.PropertyType)), null); } else { throw new Exception("genericTypeDefinition != typeof(Nullable<>)"); } } //3、原地址:https://blog.csdn.net/hebbers/article/details/78957569 //Type type = p.PropertyType; //if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))//判断convertsionType是否为nullable泛型类 //{ // //如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换 // System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(type); // //将type转换为nullable对的基础基元类型 // type = nullableConverter.UnderlyingType; //} //p.SetValue(entity, Convert.ChangeType(cellvalue, type), null); //2、自定义 这种很傻,但当前解决速度最快 //if (p.PropertyType.Name.Equals("Int32")) //{ // p.SetValue(entity, Convert.ToInt32(value), null); //} //else if (p.PropertyType.Name.Equals("String")) //{ // p.SetValue(entity, Convert.ToString(value), null); //} //else if (p.PropertyType.Name.Equals("Nullable`1")) //{ // p.SetValue(entity, Convert.ToInt32(value), null); //} ////其它类型 暂时不管 //1、字段不为空可以用这种 //p.SetValue(entity, value, null); } }); entities.Add(entity); } return entities; } public static List<T> DataTableToEntities2<T>(this DataTable dt) where T : class, new() { if (null == dt || dt.Rows.Count == 0) { return null; } List<T> entities = new List<T>(); foreach (DataRow row in dt.Rows) { PropertyInfo[] pArray = typeof(T).GetProperties(); T entity = new T(); Array.ForEach<PropertyInfo>(pArray, p => { object cellvalue = row[p.Name]; if (cellvalue != DBNull.Value) { if (!p.PropertyType.IsGenericType) { p.SetValue(entity, Convert.ChangeType(cellvalue, p.PropertyType), null); } else { Type genericTypeDefinition = p.PropertyType.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { p.SetValue(entity, Convert.ChangeType(cellvalue, Nullable.GetUnderlyingType(p.PropertyType)), null); } else { throw new Exception("genericTypeDefinition != typeof(Nullable<>)"); } } } }); entities.Add(entity); } return entities; } public static List<T> DataTableToEntities3<T>(DataTable dt) where T : class, new() { if (null == dt || dt.Rows.Count == 0) { return null; } List<T> entities = new List<T>(); foreach (DataRow row in dt.Rows) { PropertyInfo[] pArray = typeof(T).GetProperties(); T entity = new T(); Array.ForEach<PropertyInfo>(pArray, p => { object cellvalue = row[p.Name]; if (cellvalue != DBNull.Value) { //经过了几个版本的迭代,最后一个为最新的,摘自网上,已附原文地址 //4、原地址:https://blog.csdn.net/Simon1003/article/details/80839744 if (!p.PropertyType.IsGenericType) { p.SetValue(entity, Convert.ChangeType(cellvalue, p.PropertyType), null); } else { Type genericTypeDefinition = p.PropertyType.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { p.SetValue(entity, Convert.ChangeType(cellvalue, Nullable.GetUnderlyingType(p.PropertyType)), null); } else { throw new Exception("genericTypeDefinition != typeof(Nullable<>)"); } } //3、原地址:https://blog.csdn.net/hebbers/article/details/78957569 //Type type = p.PropertyType; //if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))//判断convertsionType是否为nullable泛型类 //{ // //如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换 // System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(type); // //将type转换为nullable对的基础基元类型 // type = nullableConverter.UnderlyingType; //} //p.SetValue(entity, Convert.ChangeType(cellvalue, type), null); //2、自定义 这种很傻,但当前解决速度最快 //if (p.PropertyType.Name.Equals("Int32")) //{ // p.SetValue(entity, Convert.ToInt32(value), null); //} //else if (p.PropertyType.Name.Equals("String")) //{ // p.SetValue(entity, Convert.ToString(value), null); //} //else if (p.PropertyType.Name.Equals("Nullable`1")) //{ // p.SetValue(entity, Convert.ToInt32(value), null); //} ////其它类型 暂时不管 //1、字段不为空可以用这种 //p.SetValue(entity, value, null); } }); entities.Add(entity); } return entities; } /// <summary> /// 跟属性赋值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="model"></param> /// <param name="name"></param> /// <param name="value"></param> public static void AssignValueToAttribute<T>(T model, string name, object value) { Type t = model.GetType(); var p = t.GetProperty(name); if (!p.PropertyType.IsGenericType) { p.SetValue(model, Convert.ChangeType(value, p.PropertyType), null); } else { Type genericTypeDefinition = p.PropertyType.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { p.SetValue(model, Convert.ChangeType(value, Nullable.GetUnderlyingType(p.PropertyType)), null); } else { throw new Exception("genericTypeDefinition != typeof(Nullable<>)"); } } } /// <summary> /// 获取属性值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="model"></param> /// <param name="name"></param> /// <returns></returns> public static object GetValueByAttribute<T>(T model, string name) { Type t = model.GetType(); var p = t.GetProperty(name); return p.GetValue(model, null); } /// <summary> /// 跟属性赋值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="model"></param> /// <param name="name"></param> /// <param name="model_old"></param> public static void AssignValueToAttribute<T>(T model, string name, T model_old) { Type t = model_old.GetType(); var p = t.GetProperty(name); object obj = p.GetValue(model_old, null); AssignValueToAttribute(model, name, obj); } } }