CommonUtil.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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>(string fileName = null) 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 = $"{(string.IsNullOrEmpty(fileName) ? typeof(T).Name : fileName)}.xlsx" };
  103. }
  104. /// <summary>
  105. /// 导出数据excel
  106. /// </summary>
  107. /// <returns></returns>
  108. public static async Task<IActionResult> ExportExcelData<T>(ICollection<T> data, string fileName = null) 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 = $"{(string.IsNullOrEmpty(fileName) ? typeof(T).Name : fileName)}.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. var 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. var 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. continue;
  220. var map = dict.Value.Item1;
  221. if (map != null && map.ContainsKey(sourceVal.ToString()))
  222. {
  223. var newVal = map[sourceVal.ToString()];
  224. targeProp.SetValue(newData, newVal);
  225. }
  226. else
  227. {
  228. if (targeProp.PropertyType.FullName == propertyInfo.PropertyType.FullName)
  229. {
  230. targeProp.SetValue(newData, sourceVal);
  231. }
  232. else
  233. {
  234. var newVal = sourceVal.ToString().ParseTo(targeProp.PropertyType);
  235. targeProp.SetValue(newData, newVal);
  236. }
  237. }
  238. }
  239. }
  240. if (action != null)
  241. newData = action(item, newData);
  242. if (newData != null)
  243. result.Add(newData);
  244. }
  245. return result;
  246. }
  247. /// <summary>
  248. /// 获取导入属性映射
  249. /// </summary>
  250. /// <typeparam name="TSource"></typeparam>
  251. /// <typeparam name="TTarget"></typeparam>
  252. /// <returns>整理导入对象的 属性名称, 字典数据,原属性信息,目标属性信息 </returns>
  253. private static Dictionary<string, Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>> GetImportPropertMap<TSource, TTarget>() where TTarget : new()
  254. {
  255. // 整理导入对象的属性名称,<字典数据,原属性信息,目标属性信息>
  256. var propMappings = new Dictionary<string, Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>>();
  257. var dictService = App.GetService<SqlSugarRepository<SysDictData>>();
  258. var tSourceProps = typeof(TSource).GetProperties().ToList();
  259. var tTargetProps = typeof(TTarget).GetProperties().ToDictionary(m => m.Name);
  260. foreach (var propertyInfo in tSourceProps)
  261. {
  262. var attrs = propertyInfo.GetCustomAttribute<ImportDictAttribute>();
  263. if (attrs != null && !string.IsNullOrWhiteSpace(attrs.TypeCode))
  264. {
  265. var targetProp = tTargetProps[attrs.TargetPropName];
  266. var mappingValues = dictService.Context.Queryable<SysDictType, SysDictData>((a, b) =>
  267. new JoinQueryInfos(JoinType.Inner, a.Id == b.DictTypeId))
  268. .Where(a => a.Code == attrs.TypeCode)
  269. .Where((a, b) => a.Status == StatusEnum.Enable && b.Status == StatusEnum.Enable)
  270. .Select((a, b) => new
  271. {
  272. Label = b.Value,
  273. Value = b.Code
  274. }).ToList()
  275. .ToDictionary(m => m.Label, m => m.Value.ParseTo(targetProp.PropertyType));
  276. propMappings.Add(propertyInfo.Name, new Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>(mappingValues, propertyInfo, targetProp));
  277. }
  278. else
  279. {
  280. propMappings.Add(propertyInfo.Name, new Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>(
  281. null, propertyInfo, tTargetProps.ContainsKey(propertyInfo.Name) ? tTargetProps[propertyInfo.Name] : null));
  282. }
  283. }
  284. return propMappings;
  285. }
  286. /// <summary>
  287. /// 获取导出属性映射
  288. /// </summary>
  289. /// <typeparam name="TSource"></typeparam>
  290. /// <typeparam name="TTarget"></typeparam>
  291. /// <returns>整理导入对象的 属性名称, 字典数据,原属性信息,目标属性信息 </returns>
  292. private static Dictionary<string, Tuple<Dictionary<object, string>, PropertyInfo, PropertyInfo>> GetExportPropertMap<TSource, TTarget>() where TTarget : new()
  293. {
  294. // 整理导入对象的属性名称,<字典数据,原属性信息,目标属性信息>
  295. var propMappings = new Dictionary<string, Tuple<Dictionary<object, string>, PropertyInfo, PropertyInfo>>();
  296. var dictService = App.GetService<SqlSugarRepository<SysDictData>>();
  297. var targetProps = typeof(TTarget).GetProperties().ToList();
  298. var sourceProps = typeof(TSource).GetProperties().ToDictionary(m => m.Name);
  299. foreach (var propertyInfo in targetProps)
  300. {
  301. var attrs = propertyInfo.GetCustomAttribute<ImportDictAttribute>();
  302. if (attrs != null && !string.IsNullOrWhiteSpace(attrs.TypeCode))
  303. {
  304. var targetProp = sourceProps[attrs.TargetPropName];
  305. var mappingValues = dictService.Context.Queryable<SysDictType, SysDictData>((a, b) =>
  306. new JoinQueryInfos(JoinType.Inner, a.Id == b.DictTypeId))
  307. .Where(a => a.Code == attrs.TypeCode)
  308. .Where((a, b) => a.Status == StatusEnum.Enable && b.Status == StatusEnum.Enable)
  309. .Select((a, b) => new
  310. {
  311. Label = b.Value,
  312. Value = b.Code
  313. }).ToList()
  314. .ToDictionary(m => m.Value.ParseTo(targetProp.PropertyType), m => m.Label);
  315. propMappings.Add(propertyInfo.Name, new Tuple<Dictionary<object, string>, PropertyInfo, PropertyInfo>(mappingValues, targetProp, propertyInfo));
  316. }
  317. else
  318. {
  319. propMappings.Add(propertyInfo.Name, new Tuple<Dictionary<object, string>, PropertyInfo, PropertyInfo>(
  320. null, sourceProps.ContainsKey(propertyInfo.Name) ? sourceProps[propertyInfo.Name] : null, propertyInfo));
  321. }
  322. }
  323. return propMappings;
  324. }
  325. /// <summary>
  326. /// 获取属性映射
  327. /// </summary>
  328. /// <typeparam name="TTarget"></typeparam>
  329. /// <returns>整理导入对象的 属性名称, 字典数据,原属性信息,目标属性信息 </returns>
  330. private static Dictionary<string, Tuple<string, string>> GetExportDicttMap<TTarget>() where TTarget : new()
  331. {
  332. // 整理导入对象的属性名称,目标属性名,字典Code
  333. var propMappings = new Dictionary<string, Tuple<string, string>>();
  334. var tTargetProps = typeof(TTarget).GetProperties();
  335. foreach (var propertyInfo in tTargetProps)
  336. {
  337. var attrs = propertyInfo.GetCustomAttribute<ImportDictAttribute>();
  338. if (attrs != null && !string.IsNullOrWhiteSpace(attrs.TypeCode))
  339. {
  340. propMappings.Add(propertyInfo.Name, new Tuple<string, string>(attrs.TargetPropName, attrs.TypeCode));
  341. }
  342. }
  343. return propMappings;
  344. }
  345. }