CommonUtil.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. /// <param name="fileName"></param>
  98. /// <returns></returns>
  99. public static async Task<IActionResult> ExportExcelTemplate<T>(string fileName) where T : class, new()
  100. {
  101. fileName = $"{fileName}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  102. IImporter importer = new ExcelImporter();
  103. var res = await importer.GenerateTemplate<T>(Path.Combine(App.WebHostEnvironment.WebRootPath, fileName));
  104. return new FileStreamResult(new FileStream(res.FileName, FileMode.Open), "application/octet-stream") { FileDownloadName = fileName };
  105. }
  106. /// <summary>
  107. /// 导出模板Excel
  108. /// </summary>
  109. /// <param name="fileName"></param>
  110. /// <param name="fileDto"></param>
  111. /// <returns></returns>
  112. public static async Task<IActionResult> ExportExcelTemplate(string fileName, dynamic fileDto)
  113. {
  114. MethodInfo generateTemplateMethod = typeof(CommonUtil).GetMethods().FirstOrDefault(p => p.Name == "ExportExcelTemplate" && p.IsGenericMethodDefinition);
  115. MethodInfo closedGenerateTemplateMethod = generateTemplateMethod.MakeGenericMethod(fileDto.GetType());
  116. return await (Task<IActionResult>)closedGenerateTemplateMethod.Invoke(null, new object[] { fileName });
  117. }
  118. /// <summary>
  119. /// 导入数据Excel
  120. /// </summary>
  121. /// <typeparam name="T"></typeparam>
  122. /// <param name="file"></param>
  123. /// <param name="importResultCallback"></param>
  124. /// <returns></returns>
  125. public static async Task<ICollection<T>> ImportExcelData<T>([Required] IFormFile file, Func<ImportResult<T>, ImportResult<T>> importResultCallback = null) where T : class, new()
  126. {
  127. var newFile = await App.GetRequiredService<SysFileService>().UploadFile(file, "");
  128. var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, newFile.FilePath, newFile.Id.ToString() + newFile.Suffix);
  129. var errorFileUrl = Path.Combine(newFile.FilePath, newFile.Id.ToString() + "_" + newFile.Suffix);
  130. IImporter importer = new ExcelImporter();
  131. var res = await importer.Import<T>(filePath, importResultCallback);
  132. if (res == null || res.Exception != null)
  133. throw Oops.Oh("导入异常:" + res.Exception);
  134. if (res.HasError)
  135. {
  136. if (res.TemplateErrors.Count > 0)
  137. {
  138. throw Oops.Oh("导入模板格式错误");
  139. }
  140. else
  141. {
  142. throw Oops.Oh($"请下载错误文件,根据提示修改后再次导入,<a href='{errorFileUrl}' target='_blank'>点击下载</a>");
  143. }
  144. }
  145. return res.Data;
  146. }
  147. /// <summary>
  148. /// 导入数据Excel
  149. /// </summary>
  150. /// <param name="file"></param>
  151. /// <param name="dataDto"></param>
  152. /// <returns></returns>
  153. public static async Task<dynamic> ImportExcelData([Required] IFormFile file, dynamic dataDto)
  154. {
  155. MethodInfo importMethod = typeof(CommonUtil).GetMethods().FirstOrDefault(p => p.Name == "ImportExcelData" && p.IsGenericMethodDefinition);
  156. MethodInfo closedImportMethod = importMethod.MakeGenericMethod(dataDto.GetType());
  157. var parameters = importMethod.GetParameters();
  158. var task = (Task)closedImportMethod.Invoke(null, new object[] { file, parameters[1].DefaultValue });
  159. await task;
  160. return task.GetType().GetProperty("Result").GetValue(task);
  161. }
  162. }