CsvToListData.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using Uninpho.DBOperation.Model;
  11. namespace Uninpho.Tools.components
  12. {
  13. /// <summary>
  14. /// CSV文件导入数据库工具类
  15. /// </summary>
  16. static class CsvToListData
  17. {
  18. public static List<T_xxxw_csvdata> Listdata_csvdata { get; set; }
  19. public static List<T_xxxw_csvlist> Listdata_csvlist { get; set; }
  20. /// <summary>
  21. /// csv文件转datatable
  22. /// </summary>
  23. public static void CsvToDataTable(TableName tablename)
  24. {
  25. OpenFileDialog fd = new OpenFileDialog();//首先根据打开文件对话框,选择excel表格
  26. fd.Filter = "表格|*.csv";//打开文件对话框筛选器
  27. string strPath;//文件完整的路径名
  28. if (fd.ShowDialog() == DialogResult.OK)
  29. {
  30. try
  31. {
  32. strPath = fd.FileName;
  33. DataTable datatable = new DataTable();
  34. FileStream fileStream = new FileStream(strPath, FileMode.Open, FileAccess.Read, FileShare.Read);
  35. StreamReader streamReader = new StreamReader(strPath, Encoding.GetEncoding("gb2312"));
  36. string strLine = ""; //记录每次读取的一行记录
  37. string[] arrayLine = null; //每行字段的内容
  38. string[] tableHead = null; //表头内容
  39. int columnCount = 0;//记录列数
  40. bool IsFrist = true; //判断表头
  41. while ((strLine = streamReader.ReadLine()) != null)
  42. {
  43. if (IsFrist == true)
  44. {
  45. tableHead = strLine.Split(',');
  46. IsFrist = false;
  47. columnCount = tableHead.Length;
  48. //创建列
  49. for (int i = 0; i < columnCount; i++)
  50. {
  51. DataColumn dataColumn = new DataColumn(tableHead[i]);
  52. datatable.Columns.Add(dataColumn);
  53. }
  54. }
  55. else
  56. {
  57. arrayLine = strLine.Split(',');
  58. DataRow dataRow = datatable.NewRow();
  59. for (int j = 0; j < columnCount; j++)
  60. {
  61. dataRow[j] = arrayLine[j];
  62. }
  63. datatable.Rows.Add(dataRow);
  64. }
  65. }
  66. if (arrayLine != null && arrayLine.Length > 0)
  67. {
  68. datatable.DefaultView.Sort = tableHead[0];
  69. }
  70. streamReader.Close();
  71. streamReader.Dispose();
  72. fileStream.Close();
  73. fileStream.Dispose();
  74. //此处是导入到数据表中,导入dev中需要修改,读取到的数据是datatable;
  75. //转成list导入数据库参考三张表导入功能
  76. switch (tablename)
  77. {
  78. case TableName.T_xxxw_csvdata:
  79. Listdata_csvdata = DataTableToList<T_xxxw_csvdata>(datatable, TableName.T_xxxw_csvdata);
  80. //生成唯一编码id
  81. foreach (var item in Listdata_csvdata)
  82. {
  83. string uuid = System.Guid.NewGuid().ToString("N");
  84. item.Id = uuid;
  85. }
  86. break;
  87. case TableName.T_xxxw_csvlist:
  88. Listdata_csvlist = DataTableToList<T_xxxw_csvlist>(datatable, TableName.T_xxxw_csvlist);
  89. //生成唯一编码id
  90. foreach (var item in Listdata_csvlist)
  91. {
  92. string uuid = System.Guid.NewGuid().ToString("N");
  93. item.Id = uuid;
  94. }
  95. break;
  96. default: break;
  97. }
  98. }
  99. catch (Exception ex)
  100. {
  101. MessageBox.Show(ex.Message);//捕捉异常
  102. }
  103. }
  104. }
  105. /// <summary>
  106. /// datatable转成实体类
  107. /// </summary>
  108. /// <typeparam name="T">实体类</typeparam>
  109. /// <param name="dt">datatable数据</param>
  110. /// <returns></returns>
  111. private static List<T> DataTableToList<T>(DataTable dt, TableName tablename) where T : class, new()
  112. {
  113. //需要建立辅助类
  114. Assist_xxxwcsvdata assist_xxxwcsvdata = new Assist_xxxwcsvdata();
  115. Assist_xxxwcsvlist assist_xxxwcsvlist = new Assist_xxxwcsvlist();
  116. if (dt == null || dt.Rows.Count == 0)
  117. return null;
  118. List<T> result = new List<T>();
  119. foreach (DataRow dr in dt.Rows)
  120. {
  121. try
  122. {
  123. T res = new T();
  124. for (int i = 0; i < dr.Table.Columns.Count; i++)
  125. {
  126. PropertyInfo propertyInfo = null;
  127. switch (tablename)
  128. {
  129. case TableName.T_xxxw_csvdata:
  130. propertyInfo = res.GetType().GetProperty(GetTypeValue(dr.Table.Columns[i].ColumnName, assist_xxxwcsvdata), BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
  131. break;
  132. case TableName.T_xxxw_csvlist:
  133. propertyInfo = res.GetType().GetProperty(GetTypeValue(dr.Table.Columns[i].ColumnName, assist_xxxwcsvlist), BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
  134. break;
  135. default: break;
  136. }
  137. if (propertyInfo != null)
  138. {
  139. var value = dr[i];
  140. switch (propertyInfo.PropertyType.FullName)
  141. {
  142. case "System.Decimal":
  143. if (value == DBNull.Value) { propertyInfo.SetValue(res, 0.0, null); break; }
  144. propertyInfo.SetValue(res, Convert.ToDecimal(value), null); break;
  145. case "System.String":
  146. if (value == DBNull.Value) { propertyInfo.SetValue(res, "-", null); break; }
  147. propertyInfo.SetValue(res, value.ToString(), null); break;
  148. case "System.Int32":
  149. if (value == DBNull.Value) { propertyInfo.SetValue(res, 0, null); break; }
  150. propertyInfo.SetValue(res, Convert.ToInt32(value), null); break;
  151. case "System.Double":
  152. if (value == DBNull.Value) { propertyInfo.SetValue(res, 0.0, null); break; }
  153. propertyInfo.SetValue(res, Convert.ToDouble(value), null); break;
  154. default:
  155. propertyInfo.SetValue(res, value, null); break;
  156. }
  157. }
  158. }
  159. result.Add(res);
  160. }
  161. catch (Exception ex)
  162. {
  163. ex = new Exception(string.Format("请检查第{0}行数据", result.Count + 2));
  164. throw ex;
  165. }
  166. }
  167. return result;
  168. }
  169. /// <summary>
  170. /// 辅助类转化器
  171. /// </summary>
  172. /// <typeparam name="T">类</typeparam>
  173. /// <param name="s">属性值</param>
  174. /// <param name="t">实例化类</param>
  175. /// <returns></returns>
  176. private static string GetTypeValue<T>(string s, T t)
  177. {
  178. string columnName = "";
  179. Type assistType = t.GetType();
  180. PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
  181. for (int i = 0; i < assistType.GetFields().Length; i++)
  182. {
  183. if (assistType.GetFields()[i] != null)
  184. {
  185. if (assistType.GetFields()[i].GetValue(t) != null && assistType.GetFields()[i].GetValue(t).ToString() == s)
  186. {
  187. columnName = assistType.GetFields()[i].Name;
  188. //Debug.LogError(assistType.GetFields()[i].Name);
  189. break;
  190. }
  191. }
  192. }
  193. return columnName;
  194. }
  195. }
  196. }