CommonUtil.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. // 麻省理工学院许可证
  2. //
  3. // 版权所有 (c) 2021-2023 zuohuaijun,大名科技(天津)有限公司 联系电话/微信:18020030720 QQ:515096995
  4. //
  5. // 特此免费授予获得本软件的任何人以处理本软件的权利,但须遵守以下条件:在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
  6. //
  7. // 软件按“原样”提供,不提供任何形式的明示或暗示的保证,包括但不限于对适销性、适用性和非侵权的保证。
  8. // 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是因合同、侵权或其他方式引起的,与软件或其使用或其他交易有关。
  9. using Magicodes.ExporterAndImporter.Core;
  10. using Magicodes.ExporterAndImporter.Excel;
  11. using System.Xml;
  12. using System.Xml.Linq;
  13. using System.Xml.Serialization;
  14. namespace Admin.NET.Core;
  15. /// <summary>
  16. /// 通用工具类
  17. /// </summary>
  18. public static class CommonUtil
  19. {
  20. /// <summary>
  21. /// 生成百分数
  22. /// </summary>
  23. /// <param name="PassCount"></param>
  24. /// <param name="allCount"></param>
  25. /// <returns></returns>
  26. public static string ExecPercent(decimal PassCount, decimal allCount)
  27. {
  28. string res = "";
  29. if (allCount > 0)
  30. {
  31. var value = (double)Math.Round(PassCount / allCount * 100, 1);
  32. if (value < 0)
  33. res = Math.Round(value + 5 / Math.Pow(10, 0 + 1), 0, MidpointRounding.AwayFromZero).ToString();
  34. else
  35. res = Math.Round(value, 0, MidpointRounding.AwayFromZero).ToString();
  36. }
  37. if (res == "") res = "0";
  38. return res + "%";
  39. }
  40. /// <summary>
  41. /// 获取服务地址
  42. /// </summary>
  43. /// <returns></returns>
  44. public static string GetLocalhost()
  45. {
  46. return $"{App.HttpContext.Request.Scheme}://{App.HttpContext.Request.Host.Value}";
  47. }
  48. /// <summary>
  49. /// 对象序列化XML
  50. /// </summary>
  51. /// <typeparam name="T"></typeparam>
  52. /// <param name="obj"></param>
  53. /// <returns></returns>
  54. public static string SerializeObjectToXml<T>(T obj)
  55. {
  56. if (obj == null) return string.Empty;
  57. var xs = new XmlSerializer(obj.GetType());
  58. var stream = new MemoryStream();
  59. var setting = new XmlWriterSettings
  60. {
  61. Encoding = new UTF8Encoding(false), // 不包含BOM
  62. Indent = true // 设置格式化缩进
  63. };
  64. using (var writer = XmlWriter.Create(stream, setting))
  65. {
  66. var ns = new XmlSerializerNamespaces();
  67. ns.Add("", ""); // 去除默认命名空间
  68. xs.Serialize(writer, obj, ns);
  69. }
  70. return Encoding.UTF8.GetString(stream.ToArray());
  71. }
  72. /// <summary>
  73. /// 字符串转XML格式
  74. /// </summary>
  75. /// <param name="xmlStr"></param>
  76. /// <returns></returns>
  77. public static XElement SerializeStringToXml(string xmlStr)
  78. {
  79. try
  80. {
  81. return XElement.Parse(xmlStr);
  82. }
  83. catch
  84. {
  85. return null;
  86. }
  87. }
  88. /// <summary>
  89. /// 导出模板Excel
  90. /// </summary>
  91. /// <param name="fileName"></param>
  92. /// <param name="fileDto"></param>
  93. /// <returns></returns>
  94. public static async Task<IActionResult> ExportExcelTemplate(string fileName, dynamic fileDto)
  95. {
  96. fileName = $"{fileName}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  97. IImporter importer = new ExcelImporter();
  98. MethodInfo generateTemplateMethod = typeof(ExcelImporter).GetMethod("GenerateTemplate");
  99. MethodInfo closedGenerateTemplateMethod = generateTemplateMethod.MakeGenericMethod(fileDto.GetType());
  100. var res = await (Task<dynamic>)closedGenerateTemplateMethod.Invoke(importer, new object[] { Path.Combine(App.WebHostEnvironment.WebRootPath, fileName) });
  101. return new FileStreamResult(new FileStream(res.FileName, FileMode.Open), "application/octet-stream") { FileDownloadName = fileName };
  102. }
  103. /// <summary>
  104. /// 导入数据Excel
  105. /// </summary>
  106. /// <param name="file"></param>
  107. /// <param name="dataDto"></param>
  108. /// <returns></returns>
  109. public static async Task<dynamic> ImportExcelData([Required] IFormFile file, dynamic dataDto)
  110. {
  111. var newFile = await App.GetRequiredService<SysFileService>().UploadFile(file, "");
  112. var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, newFile.FilePath, newFile.Name);
  113. IImporter importer = new ExcelImporter();
  114. MethodInfo importMethod = typeof(ExcelImporter).GetMethod("Import");
  115. MethodInfo closedImportMethod = importMethod.MakeGenericMethod(dataDto.GetType());
  116. var res = await (Task<dynamic>)closedImportMethod.Invoke(importer, new object[] { filePath });
  117. if (res == null || res.Exception != null)
  118. throw Oops.Oh("导入异常:" + res.Exception);
  119. return res.Data;
  120. }
  121. }