ExcelExtension.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. using OfficeOpenXml;
  2. using OfficeOpenXml.Drawing;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using OfficeOpenXml.Style;
  10. namespace Masuit.Tools.Excel;
  11. public static class ExcelExtension
  12. {
  13. static ExcelExtension()
  14. {
  15. ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  16. }
  17. /// <summary>
  18. /// 将内存表自动填充到Excel
  19. /// </summary>
  20. /// <param name="sheetTables">sheet名和内存表的映射</param>
  21. /// <param name="password">密码</param>
  22. /// <param name="settings">列设置</param>
  23. /// <returns>内存流</returns>
  24. public static MemoryStream ToExcel(this Dictionary<string, DataTable> sheetTables, string password = null, ColumnSettings settings = null)
  25. {
  26. using var pkg = new ExcelPackage();
  27. foreach (var pair in sheetTables)
  28. {
  29. pair.Value.TableName = pair.Key;
  30. CreateWorksheet(pkg, pair.Value, settings);
  31. }
  32. return SaveAsStream(pkg, password);
  33. }
  34. /// <summary>
  35. /// 将内存表自动填充到Excel
  36. /// </summary>
  37. /// <param name="tables">内存表</param>
  38. /// <param name="password">密码</param>
  39. /// <returns>内存流</returns>
  40. public static MemoryStream ToExcel(this List<DataTable> tables, string password = null, ColumnSettings settings = null)
  41. {
  42. using var pkg = new ExcelPackage();
  43. foreach (var table in tables)
  44. {
  45. CreateWorksheet(pkg, table, settings);
  46. }
  47. return SaveAsStream(pkg, password);
  48. }
  49. /// <summary>
  50. /// 将内存表自动填充到Excel
  51. /// </summary>
  52. /// <param name="table">内存表</param>
  53. /// <param name="password">密码</param>
  54. /// <returns>内存流</returns>
  55. public static MemoryStream ToExcel(this DataTable table, string password = null, ColumnSettings settings = null)
  56. {
  57. using var pkg = new ExcelPackage();
  58. CreateWorksheet(pkg, table, settings);
  59. return SaveAsStream(pkg, password);
  60. }
  61. private static MemoryStream SaveAsStream(ExcelPackage pkg, string password)
  62. {
  63. var ms = new MemoryStream();
  64. if (!string.IsNullOrEmpty(password))
  65. {
  66. pkg.SaveAs(ms, password);
  67. }
  68. else
  69. {
  70. pkg.SaveAs(ms);
  71. }
  72. return ms;
  73. }
  74. public static void CreateWorksheet(this ExcelPackage pkg, DataTable table, ColumnSettings settings = null)
  75. {
  76. if (string.IsNullOrEmpty(table.TableName))
  77. {
  78. table.TableName = "Sheet1";
  79. }
  80. pkg.Workbook.Worksheets.Add(table.TableName);
  81. var sheet = pkg.Workbook.Worksheets[table.TableName];
  82. FillWorksheet(sheet, table, settings);
  83. sheet.Cells.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
  84. //打印方向:纵向
  85. sheet.PrinterSettings.Orientation = eOrientation.Landscape;
  86. //集中在一页里打印
  87. sheet.PrinterSettings.FitToPage = true;
  88. //使用A4纸
  89. sheet.PrinterSettings.PaperSize = ePaperSize.A4;
  90. }
  91. /// <summary>
  92. /// 从datatable填充工作簿
  93. /// </summary>
  94. /// <param name="sheet">工作簿</param>
  95. /// <param name="table">数据</param>
  96. /// <param name="settings">列设置</param>
  97. /// <param name="startRow">起始行,默认第一行</param>
  98. /// <param name="startColumn">起始列,默认第一列A列</param>
  99. public static void FillWorksheet(this ExcelWorksheet sheet, DataTable table, ColumnSettings settings = null, int startRow = 1, int startColumn = 1)
  100. {
  101. // 填充表头
  102. var maxWidth = new int[table.Columns.Count];
  103. for (var j = 0; j < table.Columns.Count; j++)
  104. {
  105. sheet.SetValue(startRow, j + startColumn, table.Columns[j].ColumnName);
  106. maxWidth[j] = Encoding.UTF8.GetBytes(table.Columns[j].ColumnName).Length;
  107. }
  108. sheet.Row(startRow).Style.Font.Bold = true; // 表头设置为粗体
  109. sheet.Row(startRow).Style.Font.Size = sheet.Row(startRow).Style.Font.Size * 1.11f; // 表头字号放大1.11倍
  110. sheet.Row(startRow).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
  111. sheet.Row(startRow).CustomHeight = true; // 自动调整行高
  112. sheet.Cells.AutoFitColumns(); // 表头自适应列宽
  113. sheet.Cells.Style.WrapText = true;
  114. if (settings != null)
  115. {
  116. foreach (var x in settings.ColumnTypes)
  117. {
  118. sheet.Column(x.Key).Style.Numberformat.Format = x.Value;
  119. }
  120. }
  121. // 填充内容
  122. for (var i = 0; i < table.Rows.Count; i++)
  123. {
  124. sheet.Row(i + startRow + 1).CustomHeight = true; // 自动调整行高
  125. for (var j = 0; j < table.Columns.Count; j++)
  126. {
  127. switch (table.Rows[i][j])
  128. {
  129. case Stream s:
  130. {
  131. if (s.Length > 2)
  132. {
  133. var pictureType = ImageDetector.GetPictureType(s) ?? throw new ArgumentException($"{i}行{j}列图像格式不受支持");
  134. var bmp = new ExcelImage(s, pictureType).Bounds;
  135. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), s, pictureType);
  136. picture.SetPosition(i + startRow, 3, j + startColumn - 1, 5); //设置图片显示位置
  137. var percent = Math.Round(Math.Min(12000f / bmp.Height, 100));
  138. picture.SetSize((int)percent);
  139. sheet.Row(i + startRow + 1).Height = 90;
  140. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, bmp.Width * percent / 400);
  141. }
  142. sheet.SetValue(i + startRow + 1, j + startColumn, "");
  143. break;
  144. }
  145. case IEnumerable<Stream> streams:
  146. {
  147. double sumWidth = 0;
  148. foreach (var stream in streams.Where(stream => stream.Length > 2))
  149. {
  150. var pictureType = ImageDetector.GetPictureType(stream) ?? throw new ArgumentException($"{i}行{j}列图像格式不受支持");
  151. var bmp = new ExcelImage(stream, pictureType).Bounds;
  152. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), stream, pictureType);
  153. picture.SetPosition(i + startRow, 3, j + startColumn - 1, (int)Math.Ceiling(5 + sumWidth)); //设置图片显示位置
  154. var percent = Math.Min(12000f / bmp.Height, 100);
  155. picture.SetSize((int)percent);
  156. sheet.Row(i + startRow + 1).Height = 90;
  157. sumWidth += bmp.Width * percent / 100 + 5;
  158. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, sumWidth / 5);
  159. }
  160. sheet.SetValue(i + startRow + 1, j + startColumn, "");
  161. break;
  162. }
  163. case IDictionary<string, Stream> dic:
  164. {
  165. double sumWidth = 0;
  166. foreach (var kv in dic.Where(kv => kv.Value.Length > 2))
  167. {
  168. var pictureType = ImageDetector.GetPictureType(kv.Value) ?? throw new ArgumentException($"{i}行{j}列图像格式不受支持");
  169. var bmp = new ExcelImage(kv.Value, pictureType).Bounds;
  170. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), kv.Value, pictureType, new Uri(kv.Key));
  171. picture.SetPosition(i + startRow, 3, j + startColumn - 1, (int)Math.Ceiling(5 + sumWidth)); //设置图片显示位置
  172. var percent = Math.Min(12000f / bmp.Height, 100);
  173. picture.SetSize((int)percent);
  174. sheet.Row(i + startRow + 1).Height = 90;
  175. sumWidth += bmp.Width * percent / 100 + 5;
  176. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, sumWidth / 5);
  177. }
  178. sheet.SetValue(i + startRow + 1, j + startColumn, "");
  179. break;
  180. }
  181. case IDictionary<string, MemoryStream> dic:
  182. {
  183. double sumWidth = 0;
  184. foreach (var kv in dic.Where(kv => kv.Value.Length > 2))
  185. {
  186. var pictureType = ImageDetector.GetPictureType(kv.Value) ?? throw new ArgumentException($"{i}行{j}列图像格式不受支持");
  187. var bmp = new ExcelImage(kv.Value, pictureType).Bounds;
  188. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), kv.Value, pictureType, new Uri(kv.Key));
  189. picture.SetPosition(i + startRow, 3, j + startColumn - 1, (int)Math.Ceiling(5 + sumWidth)); //设置图片显示位置
  190. var percent = Math.Min(12000f / bmp.Height, 100);
  191. picture.SetSize((int)percent);
  192. sheet.Row(i + startRow + 1).Height = 90;
  193. sumWidth += bmp.Width * percent / 100 + 5;
  194. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, sumWidth / 5);
  195. }
  196. sheet.SetValue(i + startRow + 1, j + startColumn, "");
  197. break;
  198. }
  199. default:
  200. {
  201. sheet.SetValue(i + startRow + 1, j + startColumn, table.Rows[i][j] ?? "");
  202. if (table.Rows[i][j] is ValueType)
  203. {
  204. sheet.Column(j + startColumn).AutoFit();
  205. }
  206. else
  207. {
  208. // 根据单元格内容长度来自适应调整列宽
  209. sheet.Column(j + startColumn).Width = Math.Max(Encoding.UTF8.GetBytes(table.Rows[i][j].ToString() ?? string.Empty).Length + 2, sheet.Column(j + startColumn).Width);
  210. if (sheet.Column(j + startColumn).Width > 110)
  211. {
  212. sheet.Column(j + startColumn).AutoFit(100, 110);
  213. }
  214. }
  215. break;
  216. }
  217. }
  218. }
  219. }
  220. }
  221. private static readonly NumberFormater NumberFormater = new("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1);
  222. /// <summary>
  223. /// 获取字母列
  224. /// </summary>
  225. /// <param name="sheet"></param>
  226. /// <param name="index"></param>
  227. /// <returns></returns>
  228. public static ExcelColumn Column(this ExcelWorksheet sheet, string index)
  229. {
  230. return sheet.Column((int)NumberFormater.FromString(index));
  231. }
  232. }