ExcelExtension.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. using OfficeOpenXml;
  2. using OfficeOpenXml.Drawing;
  3. using SixLabors.ImageSharp;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Data;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text;
  10. namespace Masuit.Tools.Excel
  11. {
  12. public static class ExcelExtension
  13. {
  14. static ExcelExtension()
  15. {
  16. ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  17. }
  18. /// <summary>
  19. /// 将内存表自动填充到Excel
  20. /// </summary>
  21. /// <param name="sheetTables">sheet名和内存表的映射</param>
  22. /// <param name="password">密码</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. //打印方向:纵向
  84. sheet.PrinterSettings.Orientation = eOrientation.Landscape;
  85. //集中在一页里打印
  86. sheet.PrinterSettings.FitToPage = true;
  87. //使用A4纸
  88. sheet.PrinterSettings.PaperSize = ePaperSize.A4;
  89. }
  90. /// <summary>
  91. /// 从datatable填充工作簿
  92. /// </summary>
  93. /// <param name="sheet">工作簿</param>
  94. /// <param name="table">数据</param>
  95. /// <param name="settings">列设置</param>
  96. /// <param name="startRow">起始行,默认第一行</param>
  97. /// <param name="startColumn">起始列,默认第一列A列</param>
  98. public static void FillWorksheet(this ExcelWorksheet sheet, DataTable table, ColumnSettings settings = null, int startRow = 1, int startColumn = 1)
  99. {
  100. // 填充表头
  101. var maxWidth = new int[table.Columns.Count];
  102. for (var j = 0; j < table.Columns.Count; j++)
  103. {
  104. sheet.SetValue(startRow, j + startColumn, table.Columns[j].ColumnName);
  105. maxWidth[j] = Encoding.UTF8.GetBytes(table.Columns[j].ColumnName).Length;
  106. }
  107. sheet.Row(startRow).Style.Font.Bold = true; // 表头设置为粗体
  108. sheet.Row(startRow).Style.Font.Size = sheet.Row(startRow).Style.Font.Size * 1.11f; // 表头字号放大1.11倍
  109. sheet.Row(startRow).CustomHeight = true; // 自动调整行高
  110. sheet.Cells.AutoFitColumns(); // 表头自适应列宽
  111. sheet.Cells.Style.WrapText = true;
  112. if (settings != null)
  113. {
  114. foreach (var x in settings.ColumnTypes)
  115. {
  116. sheet.Column(x.Key).Style.Numberformat.Format = x.Value;
  117. }
  118. }
  119. // 填充内容
  120. for (var i = 0; i < table.Rows.Count; i++)
  121. {
  122. sheet.Row(i + startRow + 1).CustomHeight = true; // 自动调整行高
  123. for (var j = 0; j < table.Columns.Count; j++)
  124. {
  125. switch (table.Rows[i][j])
  126. {
  127. case Stream s:
  128. {
  129. if (s.Length > 2)
  130. {
  131. var (pictureType, ms) = Detect(s);
  132. var bmp = new ExcelImage(ms, pictureType).Bounds;
  133. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), ms, pictureType);
  134. picture.SetPosition(i + startRow, 3, j + startColumn - 1, 5); //设置图片显示位置
  135. var percent = Math.Min(11000f / bmp.Height, 100);
  136. picture.SetSize((int)percent);
  137. sheet.Row(i + startRow + 1).Height = 90;
  138. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, bmp.Width * percent / 600 > 32 ? bmp.Width * percent / 600 : 32);
  139. }
  140. sheet.SetValue(i + startRow + 1, j + startColumn, "");
  141. break;
  142. }
  143. case IEnumerable<Stream> streams:
  144. {
  145. double sumWidth = 0;
  146. foreach (var stream in streams.Where(stream => stream.Length > 2))
  147. {
  148. var (pictureType, ms) = Detect(stream);
  149. var bmp = new ExcelImage(ms, pictureType).Bounds;
  150. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), ms, pictureType);
  151. picture.SetPosition(i + startRow, 3, j + startColumn - 1, (int)(5 + sumWidth)); //设置图片显示位置
  152. var percent = Math.Min(11000f / bmp.Height, 100);
  153. picture.SetSize((int)percent);
  154. sheet.Row(i + startRow + 1).Height = 90;
  155. sumWidth += bmp.Width * 1.0 * percent / 100 + 5;
  156. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, sumWidth / 6 > 32 ? sumWidth / 6 : 32);
  157. }
  158. sheet.SetValue(i + startRow + 1, j + startColumn, "");
  159. break;
  160. }
  161. case IDictionary<string, Stream> dic:
  162. {
  163. double sumWidth = 0;
  164. foreach (var kv in dic.Where(kv => kv.Value.Length > 2))
  165. {
  166. var (pictureType, ms) = Detect(kv.Value);
  167. var bmp = new ExcelImage(ms, pictureType).Bounds;
  168. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), ms, pictureType, new Uri(kv.Key));
  169. picture.SetPosition(i + startRow, 3, j + startColumn - 1, (int)(5 + sumWidth)); //设置图片显示位置
  170. var percent = Math.Min(11000f / bmp.Height, 100);
  171. picture.SetSize((int)percent);
  172. sheet.Row(i + startRow + 1).Height = 90;
  173. sumWidth += bmp.Width * 1.0 * percent / 100 + 5;
  174. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, sumWidth / 6 > 32 ? sumWidth / 6 : 32);
  175. }
  176. sheet.SetValue(i + startRow + 1, j + startColumn, "");
  177. break;
  178. }
  179. case IDictionary<string, MemoryStream> dic:
  180. {
  181. double sumWidth = 0;
  182. foreach (var kv in dic.Where(kv => kv.Value.Length > 2))
  183. {
  184. var (pictureType, ms) = Detect(kv.Value);
  185. var bmp = new ExcelImage(ms, pictureType).Bounds;
  186. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), ms, pictureType, new Uri(kv.Key));
  187. picture.SetPosition(i + startRow, 3, j + startColumn - 1, (int)(5 + sumWidth)); //设置图片显示位置
  188. var percent = Math.Min(11000f / bmp.Height, 100);
  189. picture.SetSize((int)percent);
  190. sheet.Row(i + startRow + 1).Height = 90;
  191. sumWidth += bmp.Width * 1.0 * percent / 100 + 5;
  192. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, sumWidth / 6 > 32 ? sumWidth / 6 : 32);
  193. }
  194. sheet.SetValue(i + startRow + 1, j + startColumn, "");
  195. break;
  196. }
  197. default:
  198. {
  199. sheet.SetValue(i + startRow + 1, j + startColumn, table.Rows[i][j] ?? "");
  200. if (table.Rows[i][j] is ValueType)
  201. {
  202. sheet.Column(j + startColumn).AutoFit();
  203. }
  204. else
  205. {
  206. // 根据单元格内容长度来自适应调整列宽
  207. sheet.Column(j + startColumn).Width = Math.Max(Encoding.UTF8.GetBytes(table.Rows[i][j].ToString() ?? string.Empty).Length + 2, sheet.Column(j + startColumn).Width);
  208. if (sheet.Column(j + startColumn).Width > 110)
  209. {
  210. sheet.Column(j + startColumn).AutoFit(100, 110);
  211. }
  212. }
  213. break;
  214. }
  215. }
  216. }
  217. }
  218. }
  219. private static readonly NumberFormater NumberFormater = new("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1);
  220. /// <summary>
  221. /// 检测图片格式
  222. /// </summary>
  223. /// <param name="stream"></param>
  224. /// <returns></returns>
  225. private static (ePictureType type, Stream stream) Detect(Stream stream)
  226. {
  227. try
  228. {
  229. var pictureType = Image.DetectFormat(stream).Name switch
  230. {
  231. "JPEG" => ePictureType.Jpg,
  232. "PNG" => ePictureType.Png,
  233. "GIF" => ePictureType.Gif,
  234. "BMP" => ePictureType.Bmp,
  235. "SVG" => ePictureType.Svg,
  236. "TIF" => ePictureType.Tif,
  237. "WEBP" => ePictureType.WebP,
  238. _ => default
  239. };
  240. return (pictureType, stream);
  241. }
  242. catch
  243. {
  244. var ms = new MemoryStream();
  245. using var image = Image.Load(stream);
  246. image.SaveAsWebp(ms);
  247. stream.Dispose();
  248. return (ePictureType.WebP, ms);
  249. }
  250. }
  251. /// <summary>
  252. /// 获取字母列
  253. /// </summary>
  254. /// <param name="sheet"></param>
  255. /// <param name="index"></param>
  256. /// <returns></returns>
  257. public static ExcelColumn Column(this ExcelWorksheet sheet, string index)
  258. {
  259. return sheet.Column((int)NumberFormater.FromString(index));
  260. }
  261. /// <summary>
  262. /// 获取字母列
  263. /// </summary>
  264. /// <param name="sheet"></param>
  265. /// <param name="index"></param>
  266. /// <returns></returns>
  267. public static ExcelColumn Column(this ExcelWorksheet sheet, char index)
  268. {
  269. if (index is < 'A' or > 'Z')
  270. {
  271. throw new ArgumentOutOfRangeException(nameof(index));
  272. }
  273. return sheet.Column(index - 64);
  274. }
  275. }
  276. }