Converts.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. using System;
  2. using System.IO;
  3. using OfficeOpenXml;
  4. using OfficeOpenXml.Style;
  5. using SHJX.Service.Model.Control;
  6. using System.Collections.Generic;
  7. using System.ComponentModel;
  8. using System.Data;
  9. using System.Linq;
  10. using System.Reflection;
  11. using System.Windows.Media;
  12. using LicenseContext = OfficeOpenXml.LicenseContext;
  13. namespace SHJX.Service.Common.Utils
  14. {
  15. public static class Converts
  16. {
  17. #region 颜色
  18. private static readonly BrushConverter BrushConverter = new();
  19. public static SolidColorBrush ConvertToBrush(this string colorRgb)
  20. {
  21. if (string.IsNullOrWhiteSpace(colorRgb))
  22. {
  23. throw new ArgumentNullException(colorRgb);
  24. }
  25. return (SolidColorBrush)BrushConverter.ConvertFromString(colorRgb);
  26. }
  27. #endregion
  28. #region ExcelConvert
  29. public static void ConvertToExcel(this DataTable dt, string filePath)
  30. {
  31. ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  32. using var package = new ExcelPackage();
  33. var sheet = package.Workbook.Worksheets.Add("SampleTemplate");
  34. for (int i = 0; i < dt.Columns.Count; i++)
  35. {
  36. sheet.Column(i + 1).Width = 15;
  37. }
  38. sheet.Row(1).Style.Font.Bold = true;
  39. sheet.Row(1).Style.Font.Size = 12;
  40. sheet.Row(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
  41. sheet.Row(1).Style.VerticalAlignment = ExcelVerticalAlignment.Center;
  42. for (var i = 0; i < dt.Columns.Count; i++)
  43. {
  44. sheet.SetValue(1, i + 1, dt.Columns[i].ColumnName);
  45. }
  46. string[] types = new string[] { "水样", "空白", "标定"};
  47. var typeVaildationData = sheet.DataValidations.AddListValidation("F2:F49");
  48. foreach (var item in types)
  49. {
  50. typeVaildationData.Formula.Values.Add(item);
  51. }
  52. string[] concentrations = new string[] { "高", "低" };
  53. var concentrationVaildationData = sheet.DataValidations.AddListValidation("G2:G49");
  54. foreach (var item in concentrations)
  55. {
  56. concentrationVaildationData.Formula.Values.Add(item);
  57. }
  58. //数据绑定
  59. for (var i = 0; i < dt.Rows.Count; i++)
  60. {
  61. for (var j = 0; j < dt.Columns.Count; j++)
  62. {
  63. sheet.SetValue(i + 2, j + 1, dt.Rows[i][j].GetType().IsValueType ? Convert.ToDouble(dt.Rows[i][j]) : dt.Rows[i][j].ToString());
  64. }
  65. }
  66. byte[] bin = package.GetAsByteArray();
  67. File.WriteAllBytes(filePath, bin);
  68. }
  69. /// <summary>
  70. /// 读取Excel
  71. /// </summary>
  72. /// <param name="filePath"></param>
  73. /// <param name="hasHeader"></param>
  74. /// <returns></returns>
  75. public static DataTable ReadExcel(this string filePath, bool hasHeader = true)
  76. {
  77. ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  78. using ExcelPackage package = new();
  79. using (FileStream stream = File.OpenRead(filePath))
  80. {
  81. package.Load(stream);
  82. }
  83. var ws = package.Workbook.Worksheets.First();
  84. DataTable dt = new();
  85. foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
  86. {
  87. dt.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
  88. }
  89. var startRow = hasHeader ? 2 : 1;
  90. for (var rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
  91. {
  92. var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
  93. var row = dt.NewRow();
  94. foreach (var cell in wsRow)
  95. {
  96. row[cell.Start.Column - 1] = cell.Text;
  97. }
  98. dt.Rows.Add(row);
  99. }
  100. return dt;
  101. }
  102. #endregion
  103. #region ListToDataTable
  104. public static DataTable ToDataTable<T>(this List<T> items)
  105. {
  106. DataTable dataTable = new();
  107. PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
  108. foreach (PropertyInfo prop in Props)
  109. {
  110. dataTable.Columns.Add(prop.Name);
  111. }
  112. foreach (T obj in items)
  113. {
  114. var values = new object[Props.Length];
  115. for (int i = 0; i < Props.Length; i++)
  116. {
  117. values[i] = Props[i].GetValue(obj, null);
  118. }
  119. dataTable.Rows.Add(values);
  120. }
  121. return dataTable;
  122. }
  123. #endregion
  124. #region DataTable -> List<T>
  125. /// <summary>
  126. /// 将DataTable转换为List
  127. /// </summary>
  128. /// <param name="dt"></param>
  129. /// <returns></returns>
  130. public static List<T> ConvertToList<T>(this DataTable dt) where T : class, new()
  131. {
  132. List<T> lists = new(); // 定义集合
  133. foreach (DataRow dr in dt.Rows) //遍历DataTable中所有的数据行
  134. {
  135. T t = new();
  136. PropertyInfo[] propertys = typeof(T).GetProperties(); // 获得此模型的公共属性
  137. foreach (PropertyInfo item in propertys) //遍历该对象的所有属性
  138. {
  139. object value = null;
  140. object[] attr = item.GetCustomAttributes(typeof(DescriptionAttribute), false);
  141. string description = attr.Length.Equals(0) ? item.Name : ((DescriptionAttribute)attr[0]).Description;
  142. object[] defaultValues = item.GetCustomAttributes(typeof(DefaultValueAttribute), false);
  143. //检查DataTable是否包含此列(列名等于对象的属性的Description属性)
  144. if (!dt.Columns.Contains(description))
  145. {
  146. if (defaultValues is null or { Length: 0 })
  147. {
  148. continue;
  149. }
  150. value = ((DefaultValueAttribute)defaultValues[0]).Value;
  151. }
  152. else
  153. {
  154. if (!item.CanWrite) continue; //该属性不可写,直接跳出
  155. value = dr[description];//取值
  156. }
  157. if (value.Equals(DBNull.Value))
  158. {
  159. continue;//如果空,则返回
  160. }
  161. value = item.PropertyType.FullName switch
  162. {
  163. "System.String" => value.ToString(),
  164. "System.Double" => Convert.ToDouble(value),
  165. "System.Boolean" => value.Equals("1"),
  166. "System.Int32" => Convert.ToInt32(value),
  167. _ => value,
  168. };
  169. item.SetValue(t, value, null);
  170. }
  171. lists.Add(t); //对象添加到泛型集合中
  172. }
  173. return lists;
  174. }
  175. #endregion
  176. }
  177. }