Converter.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Data;
  5. using OfficeOpenXml;
  6. using System.Reflection;
  7. using OfficeOpenXml.Style;
  8. using System.Windows.Media;
  9. using System.ComponentModel;
  10. using SHJX.Service.Model.Enums;
  11. using System.Collections.Generic;
  12. using OfficeOpenXml.DataValidation.Contracts;
  13. using LicenseContext = OfficeOpenXml.LicenseContext;
  14. using SHJX.Service.Common.Event;
  15. namespace SHJX.Service.Common.Utils
  16. {
  17. public static class Converter
  18. {
  19. #region String ConvertTo Brush
  20. private static BrushConverter _brushConverter;
  21. private static BrushConverter BrushConverter
  22. {
  23. get
  24. {
  25. if (_brushConverter is null)
  26. {
  27. _brushConverter = new();
  28. }
  29. return _brushConverter;
  30. }
  31. }
  32. public static SolidColorBrush ConvertToBrush(this string colorRgb)
  33. {
  34. return string.IsNullOrWhiteSpace(colorRgb)
  35. ? throw new ArgumentNullException(colorRgb)
  36. : (SolidColorBrush)BrushConverter.ConvertFromString(colorRgb);
  37. }
  38. #endregion
  39. #region ExcelConvert
  40. public static void ConvertToExcel(this DataTable dt, string filePath)
  41. {
  42. ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  43. using ExcelPackage package = new();
  44. ExcelWorksheet sheet = package.Workbook.Worksheets.Add("SampleTemplate");
  45. for (int i = 0; i < dt.Columns.Count; i++)
  46. {
  47. sheet.Column(i + 1).Width = 15;
  48. }
  49. sheet.Row(1).Style.Font.Bold = true;
  50. sheet.Row(1).Style.Font.Size = 12;
  51. sheet.Row(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
  52. sheet.Row(1).Style.VerticalAlignment = ExcelVerticalAlignment.Center;
  53. for (int i = 0; i < dt.Columns.Count; i++)
  54. {
  55. sheet.SetValue(1, i + 1, dt.Columns[i].ColumnName);
  56. }
  57. string[] types = new string[] { "样品", "空白" };
  58. IExcelDataValidationList vaildationData = sheet.DataValidations.AddListValidation("E2:E56");
  59. foreach (string item in types)
  60. {
  61. vaildationData.Formula.Values.Add(item);
  62. }
  63. string[] acidTypes = new string[] { "Acid", "Alkali" };
  64. IExcelDataValidationList acidData = sheet.DataValidations.AddListValidation("F2:F56");
  65. foreach (string item in acidTypes)
  66. {
  67. acidData.Formula.Values.Add(item);
  68. }
  69. //数据绑定
  70. for (int i = 0; i < dt.Rows.Count; i++)
  71. {
  72. for (int j = 0; j < dt.Columns.Count; j++)
  73. {
  74. sheet.SetValue(i + 2, j + 1, dt.Rows[i][j].GetType().IsValueType ? Convert.ToDouble(dt.Rows[i][j]) : dt.Rows[i][j].ToString());
  75. }
  76. }
  77. byte[] bytes = package.GetAsByteArray();
  78. File.WriteAllBytes(filePath, bytes);
  79. }
  80. /// <summary>
  81. /// 导出结果
  82. /// </summary>
  83. /// <param name="dt"></param>
  84. /// <param name="filePath"></param>
  85. public static void ExportResult(this DataTable dt, string filePath)
  86. {
  87. string savePath = $"{filePath}SampleResult_By_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  88. ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  89. using ExcelPackage package = new();
  90. ExcelWorksheet sheet = package.Workbook.Worksheets.Add("SampleResult");
  91. for (int i = 0; i < dt.Columns.Count; i++)
  92. {
  93. sheet.Column(i + 1).Width = 15;
  94. }
  95. sheet.Row(1).Style.Font.Bold = true;
  96. sheet.Row(1).Style.Font.Size = 12;
  97. sheet.Row(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
  98. sheet.Row(1).Style.VerticalAlignment = ExcelVerticalAlignment.Center;
  99. //表头设置
  100. for (int i = 0; i < dt.Columns.Count; i++)
  101. {
  102. sheet.SetValue(1, i + 1, dt.Columns[i].ColumnName);
  103. }
  104. //数据绑定
  105. for (int i = 0; i < dt.Rows.Count; i++)
  106. {
  107. sheet.Row(i + 2).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
  108. sheet.Row(i + 2).Style.VerticalAlignment = ExcelVerticalAlignment.Center;
  109. for (int j = 0; j < dt.Columns.Count; j++)
  110. {
  111. sheet.SetValue(i + 2, j + 1, dt.Rows[i][j].GetType().IsValueType ? Convert.ToDouble(dt.Rows[i][j]) : dt.Rows[i][j].ToString());
  112. }
  113. }
  114. byte[] bytes = package.GetAsByteArray();
  115. File.WriteAllBytes(savePath, bytes);
  116. }
  117. /// <summary>
  118. /// 读取Excel
  119. /// </summary>
  120. /// <param name="filePath"></param>
  121. /// <param name="hasHeader"></param>
  122. /// <returns></returns>
  123. public static DataTable ReadExcel(this string filePath, bool hasHeader = true)
  124. {
  125. ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  126. using ExcelPackage package = new();
  127. using (FileStream stream = File.OpenRead(filePath))
  128. {
  129. package.Load(stream);
  130. }
  131. ExcelWorksheet ws = package.Workbook.Worksheets.First();
  132. DataTable dt = new();
  133. foreach (ExcelRangeBase firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
  134. {
  135. dt.Columns.Add(hasHeader ? firstRowCell.Text : $"Column {firstRowCell.Start.Column}");
  136. }
  137. int startRow = hasHeader ? 2 : 1;
  138. for (int rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
  139. {
  140. ExcelRange wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
  141. DataRow row = dt.NewRow();
  142. foreach (ExcelRangeBase cell in wsRow)
  143. {
  144. row[cell.Start.Column - 1] = cell.Text;
  145. }
  146. dt.Rows.Add(row);
  147. }
  148. return dt;
  149. }
  150. #endregion
  151. #region ListToDataTable
  152. public static DataTable ToDataTable<T>(this List<T> items)
  153. {
  154. DataTable dataTable = new();
  155. PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
  156. foreach (PropertyInfo prop in props)
  157. {
  158. dataTable.Columns.Add(prop.Name);
  159. }
  160. foreach (T obj in items)
  161. {
  162. object[] values = new object[props.Length];
  163. for (int i = 0; i < props.Length; i++)
  164. {
  165. values[i] = props[i].GetValue(obj, null);
  166. }
  167. dataTable.Rows.Add(values);
  168. }
  169. return dataTable;
  170. }
  171. #endregion
  172. #region DataTable -> List<T>
  173. /// <summary>
  174. /// 将DataTable转换为List
  175. /// </summary>
  176. /// <param name="dt"></param>
  177. /// <returns></returns>
  178. public static List<T> ConvertToList<T>(this DataTable dt) where T : class, new()
  179. {
  180. List<T> lists = new(); // 定义集合
  181. foreach (DataRow dr in dt.Rows) //遍历DataTable中所有的数据行
  182. {
  183. T t = new();
  184. PropertyInfo[] propertys = typeof(T).GetProperties(); // 获得此模型的公共属性
  185. foreach (PropertyInfo item in propertys) //遍历该对象的所有属性
  186. {
  187. object value;
  188. object[] attr = item.GetCustomAttributes(typeof(DescriptionAttribute), false);
  189. string description = attr.Length.Equals(0) ? item.Name : ((DescriptionAttribute)attr[0]).Description;
  190. object[] defaultValues = item.GetCustomAttributes(typeof(DefaultValueAttribute), false);
  191. //检查DataTable是否包含此列(列名等于对象的属性的Description属性)
  192. if (!dt.Columns.Contains(description))
  193. {
  194. if (defaultValues is null or not { Length: 8 })
  195. {
  196. continue;
  197. }
  198. value = ((DefaultValueAttribute)defaultValues[0]).Value;
  199. }
  200. else
  201. {
  202. if (!item.CanWrite)
  203. {
  204. continue; //该属性不可写,直接跳出
  205. }
  206. value = dr[description];//取值
  207. }
  208. if (value.Equals(DBNull.Value))
  209. {
  210. continue;//如果空,则返回
  211. }
  212. value = item.PropertyType.FullName switch
  213. {
  214. "System.String" => value.ToString(),
  215. "System.Boolean" => value.Equals("1"),
  216. "System.Int32" => Convert.ToInt32(value),
  217. "System.Double" => Convert.ToDouble(value),
  218. "SHJX.Service.Model.Enums.AcidBase" => (AcidBase)Enum.Parse(typeof(AcidBase), value.ToString()!),
  219. "SHJX.Service.Model.Enums.DetailState" => (DetailState)Enum.Parse(typeof(DetailState), value.ToString()!),
  220. _ => value,
  221. };
  222. item.SetValue(t, value, null);
  223. }
  224. lists.Add(t); //对象添加到泛型集合中
  225. }
  226. return lists;
  227. }
  228. #endregion
  229. }
  230. }