CommonUtil.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using Magicodes.ExporterAndImporter.Core.Models;
  7. using System.Xml;
  8. using System.Xml.Linq;
  9. using System.Xml.Serialization;
  10. namespace Admin.NET.Core;
  11. /// <summary>
  12. /// 通用工具类
  13. /// </summary>
  14. public static class CommonUtil
  15. {
  16. /// <summary>
  17. /// 生成百分数
  18. /// </summary>
  19. /// <param name="PassCount"></param>
  20. /// <param name="allCount"></param>
  21. /// <returns></returns>
  22. public static string ExecPercent(decimal PassCount, decimal allCount)
  23. {
  24. string res = "";
  25. if (allCount > 0)
  26. {
  27. var value = (double)Math.Round(PassCount / allCount * 100, 1);
  28. if (value < 0)
  29. res = Math.Round(value + 5 / Math.Pow(10, 0 + 1), 0, MidpointRounding.AwayFromZero).ToString();
  30. else
  31. res = Math.Round(value, 0, MidpointRounding.AwayFromZero).ToString();
  32. }
  33. if (res == "") res = "0";
  34. return res + "%";
  35. }
  36. /// <summary>
  37. /// 获取服务地址
  38. /// </summary>
  39. /// <returns></returns>
  40. public static string GetLocalhost()
  41. {
  42. string result = $"{App.HttpContext.Request.Scheme}://{App.HttpContext.Request.Host.Value}";
  43. // 代理模式:获取真正的本机地址
  44. // X-Original-Host=原始请求
  45. // X-Forwarded-Server=从哪里转发过来
  46. if (App.HttpContext.Request.Headers.ContainsKey("Origin")) // 配置成完整的路径如(结尾不要带"/"),比如 https://www.abc.com
  47. result = $"{App.HttpContext.Request.Headers["Origin"]}";
  48. else if (App.HttpContext.Request.Headers.ContainsKey("X-Original")) // 配置成完整的路径如(结尾不要带"/"),比如 https://www.abc.com
  49. result = $"{App.HttpContext.Request.Headers["X-Original"]}";
  50. else if (App.HttpContext.Request.Headers.ContainsKey("X-Original-Host"))
  51. result = $"{App.HttpContext.Request.Scheme}://{App.HttpContext.Request.Headers["X-Original-Host"]}";
  52. return result;
  53. }
  54. /// <summary>
  55. /// 对象序列化XML
  56. /// </summary>
  57. /// <typeparam name="T"></typeparam>
  58. /// <param name="obj"></param>
  59. /// <returns></returns>
  60. public static string SerializeObjectToXml<T>(T obj)
  61. {
  62. if (obj == null) return string.Empty;
  63. var xs = new XmlSerializer(obj.GetType());
  64. var stream = new MemoryStream();
  65. var setting = new XmlWriterSettings
  66. {
  67. Encoding = new UTF8Encoding(false), // 不包含BOM
  68. Indent = true // 设置格式化缩进
  69. };
  70. using (var writer = XmlWriter.Create(stream, setting))
  71. {
  72. var ns = new XmlSerializerNamespaces();
  73. ns.Add("", ""); // 去除默认命名空间
  74. xs.Serialize(writer, obj, ns);
  75. }
  76. return Encoding.UTF8.GetString(stream.ToArray());
  77. }
  78. /// <summary>
  79. /// 字符串转XML格式
  80. /// </summary>
  81. /// <param name="xmlStr"></param>
  82. /// <returns></returns>
  83. public static XElement SerializeStringToXml(string xmlStr)
  84. {
  85. try
  86. {
  87. return XElement.Parse(xmlStr);
  88. }
  89. catch
  90. {
  91. return null;
  92. }
  93. }
  94. /// <summary>
  95. /// 导出模板Excel
  96. /// </summary>
  97. /// <returns></returns>
  98. public static async Task<IActionResult> ExportExcelTemplate<T>() where T : class,new()
  99. {
  100. IImporter importer = new ExcelImporter();
  101. var res=await importer.GenerateTemplateBytes<T>();
  102. return new FileContentResult(res, "application/octet-stream") { FileDownloadName = typeof(T).Name+".xlsx" };
  103. }
  104. /// <summary>
  105. /// 导出数据excel
  106. /// </summary>
  107. /// <returns></returns>
  108. public static async Task<IActionResult> ExportExcelData<T>(ICollection<T> data) where T : class, new()
  109. {
  110. var export = new ExcelExporter();
  111. var res = await export.ExportAsByteArray<T>(data);
  112. return new FileContentResult(res, "application/octet-stream") { FileDownloadName = typeof(T).Name + ".xlsx" };
  113. }
  114. /// <summary>
  115. /// 导出数据excel,包括字典转换
  116. /// </summary>
  117. /// <returns></returns>
  118. public static async Task<IActionResult> ExportExcelData<TSource, TTarget>(ISugarQueryable<TSource> query, Func<TSource, TTarget, TTarget> action = null)
  119. where TSource : class, new() where TTarget : class, new ()
  120. {
  121. var PropMappings = GetExportPropertMap< TSource, TTarget >();
  122. var data = query.ToList();
  123. //相同属性复制值,字典值转换
  124. var result = new List<TTarget>();
  125. foreach (var item in data)
  126. {
  127. var newData = new TTarget();
  128. foreach (var dict in PropMappings)
  129. {
  130. var targeProp = dict.Value.Item3;
  131. if (targeProp != null)
  132. {
  133. var propertyInfo = dict.Value.Item2;
  134. var sourceVal = propertyInfo.GetValue(item, null);
  135. if (sourceVal == null)
  136. {
  137. continue;
  138. }
  139. var map = dict.Value.Item1;
  140. if (map != null && map.ContainsKey(sourceVal))
  141. {
  142. var newVal = map[sourceVal];
  143. targeProp.SetValue(newData, newVal);
  144. }
  145. else
  146. {
  147. if (targeProp.PropertyType.FullName == propertyInfo.PropertyType.FullName)
  148. {
  149. targeProp.SetValue(newData, sourceVal);
  150. }
  151. else
  152. {
  153. var newVal = sourceVal.ToString().ParseTo(targeProp.PropertyType);
  154. targeProp.SetValue(newData, newVal);
  155. }
  156. }
  157. }
  158. if (action != null)
  159. {
  160. newData = action(item, newData);
  161. }
  162. }
  163. result.Add(newData);
  164. }
  165. var export = new ExcelExporter();
  166. var res = await export.ExportAsByteArray(result);
  167. return new FileContentResult(res, "application/octet-stream") { FileDownloadName = typeof(TTarget).Name + ".xlsx" };
  168. }
  169. /// <summary>
  170. /// 导入数据Excel
  171. /// </summary>
  172. /// <param name="file"></param>
  173. /// <returns></returns>
  174. public static async Task<ICollection<T>> ImportExcelData<T>([Required] IFormFile file) where T : class, new()
  175. {
  176. IImporter importer = new ExcelImporter();
  177. var res = await importer.Import<T>(file.OpenReadStream());
  178. string message = string.Empty;
  179. if (res.HasError)
  180. {
  181. if (res.Exception != null)
  182. message += $"\r\n{res.Exception.Message}";
  183. foreach (DataRowErrorInfo drErrorInfo in res.RowErrors)
  184. {
  185. int rowNum = drErrorInfo.RowIndex;
  186. foreach (var item in drErrorInfo.FieldErrors)
  187. message += $"\r\n{item.Key}:{item.Value}(文件第{drErrorInfo.RowIndex}行)";
  188. }
  189. message += "字段缺失:" + string.Join(",", res.TemplateErrors.Select(m => m.RequireColumnName).ToList());
  190. throw Oops.Oh("导入异常:" + message);
  191. }
  192. return res.Data;
  193. }
  194. //例:List<Dm_ApplyDemo> ls = CommonUtil.ParseList<Dm_ApplyDemoInport, Dm_ApplyDemo>(importResult.Data);
  195. /// <summary>
  196. /// 对象转换 含字典转换
  197. /// </summary>
  198. /// <typeparam name="TSource"></typeparam>
  199. /// <typeparam name="TTarget"></typeparam>
  200. /// <param name="data"></param>
  201. /// <param name="action"></param>
  202. /// <returns></returns>
  203. public static List<TTarget> ParseList<TSource, TTarget>(IEnumerable<TSource> data, Func<TSource, TTarget, TTarget> action=null) where TTarget : new()
  204. {
  205. Dictionary<string, Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>> PropMappings = GetImportPropertMap<TSource, TTarget>();
  206. //相同属性复制值,字典值转换
  207. var result = new List<TTarget>();
  208. foreach (var item in data)
  209. {
  210. var newData = new TTarget();
  211. foreach (var dict in PropMappings)
  212. {
  213. var targeProp = dict.Value.Item3;
  214. if (targeProp != null)
  215. {
  216. var propertyInfo = dict.Value.Item2;
  217. var sourceVal = propertyInfo.GetValue(item, null);
  218. if (sourceVal == null)
  219. {
  220. continue;
  221. }
  222. var map = dict.Value.Item1;
  223. if (map != null && map.ContainsKey(sourceVal.ToString()))
  224. {
  225. var newVal = map[sourceVal.ToString()];
  226. targeProp.SetValue(newData, newVal);
  227. }
  228. else
  229. {
  230. if (targeProp.PropertyType.FullName == propertyInfo.PropertyType.FullName)
  231. {
  232. targeProp.SetValue(newData, sourceVal);
  233. }
  234. else
  235. {
  236. var newVal = sourceVal.ToString().ParseTo(targeProp.PropertyType);
  237. targeProp.SetValue(newData, newVal);
  238. }
  239. }
  240. }
  241. }
  242. if (action != null)
  243. {
  244. newData = action(item, newData);
  245. }
  246. if (newData != null)
  247. result.Add(newData);
  248. }
  249. return result;
  250. }
  251. /// <summary>
  252. /// 获取导入属性映射
  253. /// </summary>
  254. /// <typeparam name="TSource"></typeparam>
  255. /// <typeparam name="TTarget"></typeparam>
  256. /// <returns>整理导入对象的 属性名称, 字典数据,原属性信息,目标属性信息 </returns>
  257. private static Dictionary<string, Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>> GetImportPropertMap<TSource, TTarget>() where TTarget : new()
  258. {
  259. var dictService = App.GetService<SqlSugarRepository<SysDictData>>();
  260. //整理导入对象的 属性名称,<字典数据,原属性信息,目标属性信息>
  261. Dictionary<string, Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>> PropMappings =
  262. new Dictionary<string, Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>>();
  263. var TSourceProps = typeof(TSource).GetProperties().ToList();
  264. var TTargetProps = typeof(TTarget).GetProperties().ToDictionary(m => m.Name);
  265. foreach (var propertyInfo in TSourceProps)
  266. {
  267. var attrs = propertyInfo.GetCustomAttribute<ImportDictAttribute>();
  268. if (attrs != null && !string.IsNullOrWhiteSpace(attrs.TypeCode))
  269. {
  270. var targetProp = TTargetProps[attrs.TargetPropName];
  271. var MappingValues = dictService.Context.Queryable<SysDictType, SysDictData>((a, b) =>
  272. new JoinQueryInfos(JoinType.Inner, a.Id == b.DictTypeId))
  273. .Where(a => a.Code == attrs.TypeCode)
  274. .Where((a, b) => a.Status == StatusEnum.Enable && b.Status == StatusEnum.Enable)
  275. .Select((a, b) => new
  276. {
  277. Label = b.Value,
  278. Value = b.Code
  279. }).ToList()
  280. .ToDictionary(m => m.Label, m => m.Value.ParseTo(targetProp.PropertyType));
  281. PropMappings.Add(propertyInfo.Name, new Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>(
  282. MappingValues, propertyInfo, targetProp
  283. ));
  284. }
  285. else
  286. {
  287. PropMappings.Add(propertyInfo.Name, new Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>(
  288. null, propertyInfo, TTargetProps.ContainsKey(propertyInfo.Name) ? TTargetProps[propertyInfo.Name] : null
  289. ));
  290. }
  291. }
  292. return PropMappings;
  293. }
  294. /// <summary>
  295. /// 获取导出属性映射
  296. /// </summary>
  297. /// <typeparam name="TSource"></typeparam>
  298. /// <typeparam name="TTarget"></typeparam>
  299. /// <returns>整理导入对象的 属性名称, 字典数据,原属性信息,目标属性信息 </returns>
  300. private static Dictionary<string, Tuple<Dictionary<object,string>, PropertyInfo, PropertyInfo>> GetExportPropertMap<TSource, TTarget>() where TTarget : new()
  301. {
  302. var dictService = App.GetService<SqlSugarRepository<SysDictData>>();
  303. //整理导入对象的 属性名称,<字典数据,原属性信息,目标属性信息>
  304. Dictionary<string, Tuple<Dictionary<object,string>, PropertyInfo, PropertyInfo>> PropMappings =
  305. new Dictionary<string, Tuple<Dictionary<object,string>, PropertyInfo, PropertyInfo>>();
  306. var TargetProps = typeof(TTarget).GetProperties().ToList();
  307. var SourceProps = typeof(TSource).GetProperties().ToDictionary(m => m.Name);
  308. foreach (var propertyInfo in TargetProps)
  309. {
  310. var attrs = propertyInfo.GetCustomAttribute<ImportDictAttribute>();
  311. if (attrs != null && !string.IsNullOrWhiteSpace(attrs.TypeCode))
  312. {
  313. var targetProp = SourceProps[attrs.TargetPropName];
  314. var MappingValues = dictService.Context.Queryable<SysDictType, SysDictData>((a, b) =>
  315. new JoinQueryInfos(JoinType.Inner, a.Id == b.DictTypeId))
  316. .Where(a => a.Code == attrs.TypeCode)
  317. .Where((a, b) => a.Status == StatusEnum.Enable && b.Status == StatusEnum.Enable)
  318. .Select((a, b) => new
  319. {
  320. Label = b.Value,
  321. Value = b.Code
  322. }).ToList()
  323. .ToDictionary(m => m.Value.ParseTo(targetProp.PropertyType), m => m.Label);
  324. PropMappings.Add(propertyInfo.Name, new Tuple<Dictionary<object,string>, PropertyInfo, PropertyInfo>(
  325. MappingValues, targetProp, propertyInfo
  326. ));
  327. }
  328. else
  329. {
  330. PropMappings.Add(propertyInfo.Name, new Tuple<Dictionary<object,string>, PropertyInfo, PropertyInfo>(
  331. null, SourceProps.ContainsKey(propertyInfo.Name) ? SourceProps[propertyInfo.Name] : null, propertyInfo
  332. ));
  333. }
  334. }
  335. return PropMappings;
  336. }
  337. /// <summary>
  338. /// 获取属性映射
  339. /// </summary>
  340. /// <typeparam name="TSource"></typeparam>
  341. /// <typeparam name="TTarget"></typeparam>
  342. /// <returns>整理导入对象的 属性名称, 字典数据,原属性信息,目标属性信息 </returns>
  343. private static Dictionary<string, Tuple<string, string>> GetExportDicttMap< TTarget>() where TTarget : new()
  344. {
  345. var dictService = App.GetService<SqlSugarRepository<SysDictData>>();
  346. //整理导入对象的 属性名称,目标属性名,字典Code
  347. Dictionary<string, Tuple<string, string>> PropMappings = new Dictionary<string, Tuple<string, string>>();
  348. var TTargetProps = typeof(TTarget).GetProperties();
  349. foreach (var propertyInfo in TTargetProps)
  350. {
  351. var attrs = propertyInfo.GetCustomAttribute<ImportDictAttribute>();
  352. if (attrs != null && !string.IsNullOrWhiteSpace(attrs.TypeCode))
  353. {
  354. PropMappings.Add(propertyInfo.Name, new Tuple<string, string>( attrs.TargetPropName,attrs.TypeCode ));
  355. }
  356. }
  357. return PropMappings;
  358. }
  359. }