ExcelExtension.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. using OfficeOpenXml;
  2. using OfficeOpenXml.Drawing;
  3. using OfficeOpenXml.Style;
  4. using OfficeOpenXml.Table;
  5. using System;
  6. using System.Collections;
  7. using System.Collections.Generic;
  8. using System.Data;
  9. using System.Drawing;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Text;
  13. namespace Masuit.Tools.Excel;
  14. public static class ExcelExtension
  15. {
  16. static ExcelExtension()
  17. {
  18. ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  19. }
  20. /// <summary>
  21. /// 将内存表自动填充到Excel
  22. /// </summary>
  23. /// <param name="sheetTables">sheet名和内存表的映射</param>
  24. /// <param name="password">密码</param>
  25. /// <param name="settings">列设置</param>
  26. /// <returns>内存流</returns>
  27. public static MemoryStream ToExcel(this Dictionary<string, DataTable> sheetTables, string password = null, ColumnSettings settings = null)
  28. {
  29. using var pkg = new ExcelPackage();
  30. foreach (var pair in sheetTables)
  31. {
  32. pair.Value.TableName = pair.Key;
  33. CreateWorksheet(pkg, pair.Value, settings);
  34. }
  35. return SaveAsStream(pkg, password);
  36. }
  37. /// <summary>
  38. /// 将内存表自动填充到Excel
  39. /// </summary>
  40. /// <param name="sheetTables">sheet名和内存表的映射</param>
  41. /// <param name="password">密码</param>
  42. /// <param name="settings">列设置</param>
  43. /// <returns>内存流</returns>
  44. public static MemoryStream ToExcel<T>(this Dictionary<string, IEnumerable<T>> sheetTables, string password = null, ColumnSettings settings = null)
  45. {
  46. using var pkg = new ExcelPackage();
  47. foreach (var pair in sheetTables)
  48. {
  49. CreateWorksheet(pkg, pair, settings);
  50. }
  51. return SaveAsStream(pkg, password);
  52. }
  53. /// <summary>
  54. /// 将内存表自动填充到Excel
  55. /// </summary>
  56. /// <param name="tables">内存表</param>
  57. /// <param name="password">密码</param>
  58. /// <returns>内存流</returns>
  59. public static MemoryStream ToExcel(this List<DataTable> tables, string password = null, ColumnSettings settings = null)
  60. {
  61. using var pkg = new ExcelPackage();
  62. foreach (var table in tables)
  63. {
  64. CreateWorksheet(pkg, table, settings);
  65. }
  66. return SaveAsStream(pkg, password);
  67. }
  68. /// <summary>
  69. /// 将内存表自动填充到Excel
  70. /// </summary>
  71. /// <param name="table">内存表</param>
  72. /// <param name="password">密码</param>
  73. /// <returns>内存流</returns>
  74. public static MemoryStream ToExcel(this DataTable table, string password = null, ColumnSettings settings = null)
  75. {
  76. using var pkg = new ExcelPackage();
  77. CreateWorksheet(pkg, table, settings);
  78. return SaveAsStream(pkg, password);
  79. }
  80. /// <summary>
  81. /// 将内存表自动填充到Excel
  82. /// </summary>
  83. /// <param name="table">内存表</param>
  84. /// <param name="password">密码</param>
  85. /// <returns>内存流</returns>
  86. public static MemoryStream ToExcel<T>(this IEnumerable<T> table, string password = null, ColumnSettings settings = null)
  87. {
  88. using var pkg = new ExcelPackage();
  89. CreateWorksheet(pkg, new KeyValuePair<string, IEnumerable<T>>("Sheet1", table), settings);
  90. return SaveAsStream(pkg, password);
  91. }
  92. private static MemoryStream SaveAsStream(ExcelPackage pkg, string password)
  93. {
  94. var ms = new MemoryStream();
  95. if (!string.IsNullOrEmpty(password))
  96. {
  97. pkg.SaveAs(ms, password);
  98. }
  99. else
  100. {
  101. pkg.SaveAs(ms);
  102. }
  103. return ms;
  104. }
  105. public static void CreateWorksheet(this ExcelPackage pkg, DataTable table, ColumnSettings settings = null)
  106. {
  107. if (string.IsNullOrEmpty(table.TableName))
  108. {
  109. table.TableName = "Sheet1";
  110. }
  111. var sheet = pkg.Workbook.Worksheets.Add(table.TableName);
  112. sheet.Cells.Style.Font.Name = "微软雅黑";
  113. FillWorksheet(sheet, table, settings);
  114. sheet.Cells.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
  115. //打印方向:纵向
  116. sheet.PrinterSettings.Orientation = eOrientation.Landscape;
  117. //集中在一页里打印
  118. sheet.PrinterSettings.FitToPage = true;
  119. //使用A4纸
  120. sheet.PrinterSettings.PaperSize = ePaperSize.A4;
  121. }
  122. public static void CreateWorksheet<T>(this ExcelPackage pkg, KeyValuePair<string, IEnumerable<T>> table, ColumnSettings settings = null)
  123. {
  124. var sheet = pkg.Workbook.Worksheets.Add(table.Key);
  125. sheet.Cells.Style.Font.Name = "微软雅黑";
  126. FillWorksheet(sheet, table.Value, settings);
  127. sheet.Cells.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
  128. //打印方向:纵向
  129. sheet.PrinterSettings.Orientation = eOrientation.Landscape;
  130. //集中在一页里打印
  131. sheet.PrinterSettings.FitToPage = true;
  132. //使用A4纸
  133. sheet.PrinterSettings.PaperSize = ePaperSize.A4;
  134. }
  135. /// <summary>
  136. /// 从datatable填充工作簿
  137. /// </summary>
  138. /// <param name="sheet">工作簿</param>
  139. /// <param name="table">数据</param>
  140. /// <param name="settings">列设置</param>
  141. /// <param name="startRow">起始行,默认第一行</param>
  142. /// <param name="startColumn">起始列,默认第一列A列</param>
  143. public static void FillWorksheet(this ExcelWorksheet sheet, DataTable table, ColumnSettings settings = null, int startRow = 1, int startColumn = 1)
  144. {
  145. var hasPicColumn = false;
  146. if (table.Rows.Count > 0)
  147. {
  148. for (int i = 0; i < table.Columns.Count; i++)
  149. {
  150. switch (table.Rows[0][i])
  151. {
  152. case Stream:
  153. case IEnumerable<Stream>:
  154. case IDictionary<string, Stream>:
  155. case IDictionary<string, MemoryStream>:
  156. hasPicColumn = true;
  157. break;
  158. }
  159. }
  160. }
  161. if (hasPicColumn)
  162. {
  163. // 填充表头
  164. var maxWidth = new int[table.Columns.Count];
  165. for (var j = 0; j < table.Columns.Count; j++)
  166. {
  167. sheet.SetValue(startRow, j + startColumn, table.Columns[j].ColumnName);
  168. maxWidth[j] = Encoding.UTF8.GetBytes(table.Columns[j].ColumnName).Length;
  169. }
  170. sheet.Row(startRow).Style.Font.Bold = true; // 表头设置为粗体
  171. sheet.Row(startRow).Style.Font.Size = sheet.Row(startRow).Style.Font.Size * 1.11f; // 表头字号放大1.11倍
  172. sheet.Row(startRow).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
  173. sheet.Row(startRow).CustomHeight = true; // 自动调整行高
  174. if (settings != null)
  175. {
  176. foreach (var x in settings.ColumnTypes)
  177. {
  178. sheet.Column(x.Key).Style.Numberformat.Format = x.Value;
  179. }
  180. }
  181. // 填充内容
  182. for (int i = 0; i < table.Rows.Count; i++)
  183. {
  184. sheet.Row(i + startRow + 1).CustomHeight = true; // 自动调整行高
  185. for (int j = 0; j < table.Columns.Count; j++)
  186. {
  187. switch (table.Rows[i][j])
  188. {
  189. case Stream s:
  190. {
  191. if (s.Length > 2)
  192. {
  193. var pictureType = ImageDetector.GetPictureType(s) ?? throw new ArgumentException($"{i}行{j}列图像格式不受支持");
  194. var bmp = new ExcelImage(s, pictureType).Bounds;
  195. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), s, pictureType);
  196. picture.SetPosition(i + startRow, 3, j + startColumn - 1, 5); //设置图片显示位置
  197. var percent = Math.Round(Math.Min(12000f / bmp.Height, 100));
  198. picture.SetSize((int)percent);
  199. sheet.Row(i + startRow + 1).Height = 90;
  200. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, bmp.Width * percent / 400);
  201. }
  202. sheet.SetValue(i + startRow + 1, j + startColumn, "");
  203. break;
  204. }
  205. case IEnumerable<Stream> streams:
  206. {
  207. double sumWidth = 0;
  208. foreach (var stream in streams.Where(stream => stream.Length > 2))
  209. {
  210. var pictureType = ImageDetector.GetPictureType(stream) ?? throw new ArgumentException($"{i}行{j}列图像格式不受支持");
  211. var bmp = new ExcelImage(stream, pictureType).Bounds;
  212. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), stream, pictureType);
  213. picture.SetPosition(i + startRow, 3, j + startColumn - 1, (int)Math.Ceiling(5 + sumWidth)); //设置图片显示位置
  214. var percent = Math.Min(12000f / bmp.Height, 100);
  215. picture.SetSize((int)percent);
  216. sheet.Row(i + startRow + 1).Height = 90;
  217. sumWidth += bmp.Width * percent / 100 + 5;
  218. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, sumWidth / 5);
  219. }
  220. sheet.SetValue(i + startRow + 1, j + startColumn, "");
  221. break;
  222. }
  223. case IDictionary<string, Stream> dic:
  224. {
  225. double sumWidth = 0;
  226. foreach (var kv in dic.Where(kv => kv.Value.Length > 2))
  227. {
  228. var pictureType = ImageDetector.GetPictureType(kv.Value) ?? throw new ArgumentException($"{i}行{j}列图像格式不受支持");
  229. var bmp = new ExcelImage(kv.Value, pictureType).Bounds;
  230. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), kv.Value, pictureType, new Uri(kv.Key));
  231. picture.SetPosition(i + startRow, 3, j + startColumn - 1, (int)Math.Ceiling(5 + sumWidth)); //设置图片显示位置
  232. var percent = Math.Min(12000f / bmp.Height, 100);
  233. picture.SetSize((int)percent);
  234. sheet.Row(i + startRow + 1).Height = 90;
  235. sumWidth += bmp.Width * percent / 100 + 5;
  236. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, sumWidth / 5);
  237. }
  238. sheet.SetValue(i + startRow + 1, j + startColumn, "");
  239. break;
  240. }
  241. case IDictionary<string, MemoryStream> dic:
  242. {
  243. double sumWidth = 0;
  244. foreach (var kv in dic.Where(kv => kv.Value.Length > 2))
  245. {
  246. var pictureType = ImageDetector.GetPictureType(kv.Value) ?? throw new ArgumentException($"{i}行{j}列图像格式不受支持");
  247. var bmp = new ExcelImage(kv.Value, pictureType).Bounds;
  248. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), kv.Value, pictureType, new Uri(kv.Key));
  249. picture.SetPosition(i + startRow, 3, j + startColumn - 1, (int)Math.Ceiling(5 + sumWidth)); //设置图片显示位置
  250. var percent = Math.Min(12000f / bmp.Height, 100);
  251. picture.SetSize((int)percent);
  252. sheet.Row(i + startRow + 1).Height = 90;
  253. sumWidth += bmp.Width * percent / 100 + 5;
  254. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, sumWidth / 5);
  255. }
  256. sheet.SetValue(i + startRow + 1, j + startColumn, "");
  257. break;
  258. }
  259. default:
  260. {
  261. sheet.SetValue(i + startRow + 1, j + startColumn, table.Rows[i][j] ?? "");
  262. if (table.Rows[i][j] is ValueType)
  263. {
  264. sheet.Column(j + startColumn).AutoFit();
  265. }
  266. else
  267. {
  268. // 根据单元格内容长度来自适应调整列宽
  269. using var bitmap = new Bitmap(1, 1);
  270. using var graphics = Graphics.FromImage(bitmap);
  271. using var font = new Font(sheet.Cells[i + startRow + 1, j + startColumn].Style.Font.Name, 1.66f);
  272. var measureText = graphics.MeasureString(table.Rows[i][j].ToString(), font);
  273. sheet.Column(j + startColumn).Width = Math.Min(110, Math.Max(measureText.Width, sheet.Column(j + startColumn).Width));
  274. }
  275. break;
  276. }
  277. }
  278. }
  279. }
  280. sheet.Cells.AutoFitColumns(); // 表头自适应列宽
  281. sheet.Cells.Style.WrapText = true;
  282. }
  283. else
  284. {
  285. sheet.Cells[startRow, startColumn].LoadFromDataTable(table, true, TableStyles.Light15).AutoFitColumns(12, 90);
  286. sheet.Cells.Style.WrapText = true;
  287. }
  288. }
  289. /// <summary>
  290. /// 从datatable填充工作簿
  291. /// </summary>
  292. /// <param name="sheet">工作簿</param>
  293. /// <param name="table">数据</param>
  294. /// <param name="settings">列设置</param>
  295. /// <param name="startRow">起始行,默认第一行</param>
  296. /// <param name="startColumn">起始列,默认第一列A列</param>
  297. public static void FillWorksheet<T>(this ExcelWorksheet sheet, IEnumerable<T> source, ColumnSettings settings = null, int startRow = 1, int startColumn = 1)
  298. {
  299. var hasPicColumn = false;
  300. var properties = typeof(T).GetProperties();
  301. if (source is ICollection<T> table)
  302. {
  303. }
  304. else
  305. {
  306. table = source.ToList();
  307. }
  308. if (table.Any())
  309. {
  310. if (properties.Any(t => t.PropertyType.IsSubclassOf(typeof(Stream)) || typeof(IDictionary).IsAssignableFrom(t.PropertyType)))
  311. {
  312. hasPicColumn = true;
  313. }
  314. }
  315. if (hasPicColumn)
  316. {
  317. // 填充表头
  318. var maxWidth = new int[properties.Length];
  319. for (var j = 0; j < properties.Length; j++)
  320. {
  321. sheet.SetValue(startRow, j + startColumn, properties[j].Name);
  322. maxWidth[j] = Encoding.UTF8.GetBytes(properties[j].Name).Length;
  323. }
  324. sheet.Row(startRow).Style.Font.Bold = true; // 表头设置为粗体
  325. sheet.Row(startRow).Style.Font.Size = sheet.Row(startRow).Style.Font.Size * 1.11f; // 表头字号放大1.11倍
  326. sheet.Row(startRow).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
  327. sheet.Row(startRow).CustomHeight = true; // 自动调整行高
  328. if (settings != null)
  329. {
  330. foreach (var x in settings.ColumnTypes)
  331. {
  332. sheet.Column(x.Key).Style.Numberformat.Format = x.Value;
  333. }
  334. }
  335. // 填充内容
  336. int current = 0;
  337. foreach (var item in table)
  338. {
  339. sheet.Row(current + startRow + 1).CustomHeight = true; // 自动调整行高
  340. for (int j = 0; j < properties.Length; j++)
  341. {
  342. switch (properties[j].GetValue(item))
  343. {
  344. case Stream s:
  345. {
  346. if (s.Length > 2)
  347. {
  348. var pictureType = ImageDetector.GetPictureType(s) ?? throw new ArgumentException($"{current}行{j}列图像格式不受支持");
  349. var bmp = new ExcelImage(s, pictureType).Bounds;
  350. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), s, pictureType);
  351. picture.SetPosition(current + startRow, 3, j + startColumn - 1, 5); //设置图片显示位置
  352. var percent = Math.Round(Math.Min(12000f / bmp.Height, 100));
  353. picture.SetSize((int)percent);
  354. sheet.Row(current + startRow + 1).Height = 90;
  355. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, bmp.Width * percent / 400);
  356. }
  357. sheet.SetValue(current + startRow + 1, j + startColumn, "");
  358. break;
  359. }
  360. case IEnumerable<Stream> streams:
  361. {
  362. double sumWidth = 0;
  363. foreach (var stream in streams.Where(stream => stream.Length > 2))
  364. {
  365. var pictureType = ImageDetector.GetPictureType(stream) ?? throw new ArgumentException($"{current}行{j}列图像格式不受支持");
  366. var bmp = new ExcelImage(stream, pictureType).Bounds;
  367. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), stream, pictureType);
  368. picture.SetPosition(current + startRow, 3, j + startColumn - 1, (int)Math.Ceiling(5 + sumWidth)); //设置图片显示位置
  369. var percent = Math.Min(12000f / bmp.Height, 100);
  370. picture.SetSize((int)percent);
  371. sheet.Row(current + startRow + 1).Height = 90;
  372. sumWidth += bmp.Width * percent / 100 + 5;
  373. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, sumWidth / 5);
  374. }
  375. sheet.SetValue(current + startRow + 1, j + startColumn, "");
  376. break;
  377. }
  378. case IDictionary<string, Stream> dic:
  379. {
  380. double sumWidth = 0;
  381. foreach (var kv in dic.Where(kv => kv.Value.Length > 2))
  382. {
  383. var pictureType = ImageDetector.GetPictureType(kv.Value) ?? throw new ArgumentException($"{current}行{j}列图像格式不受支持");
  384. var bmp = new ExcelImage(kv.Value, pictureType).Bounds;
  385. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), kv.Value, pictureType, new Uri(kv.Key));
  386. picture.SetPosition(current + startRow, 3, j + startColumn - 1, (int)Math.Ceiling(5 + sumWidth)); //设置图片显示位置
  387. var percent = Math.Min(12000f / bmp.Height, 100);
  388. picture.SetSize((int)percent);
  389. sheet.Row(current + startRow + 1).Height = 90;
  390. sumWidth += bmp.Width * percent / 100 + 5;
  391. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, sumWidth / 5);
  392. }
  393. sheet.SetValue(current + startRow + 1, j + startColumn, "");
  394. break;
  395. }
  396. case IDictionary<string, MemoryStream> dic:
  397. {
  398. double sumWidth = 0;
  399. foreach (var kv in dic.Where(kv => kv.Value.Length > 2))
  400. {
  401. var pictureType = ImageDetector.GetPictureType(kv.Value) ?? throw new ArgumentException($"{current}行{j}列图像格式不受支持");
  402. var bmp = new ExcelImage(kv.Value, pictureType).Bounds;
  403. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), kv.Value, pictureType, new Uri(kv.Key));
  404. picture.SetPosition(current + startRow, 3, j + startColumn - 1, (int)Math.Ceiling(5 + sumWidth)); //设置图片显示位置
  405. var percent = Math.Min(12000f / bmp.Height, 100);
  406. picture.SetSize((int)percent);
  407. sheet.Row(current + startRow + 1).Height = 90;
  408. sumWidth += bmp.Width * percent / 100 + 5;
  409. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, sumWidth / 5);
  410. }
  411. sheet.SetValue(current + startRow + 1, j + startColumn, "");
  412. break;
  413. }
  414. default:
  415. {
  416. sheet.SetValue(current + startRow + 1, j + startColumn, properties[j].GetValue(item) ?? "");
  417. if (properties[j].GetValue(item) is ValueType)
  418. {
  419. sheet.Column(j + startColumn).AutoFit();
  420. }
  421. else
  422. {
  423. // 根据单元格内容长度来自适应调整列宽
  424. using var bitmap = new Bitmap(1, 1);
  425. using var graphics = Graphics.FromImage(bitmap);
  426. using var font = new Font(sheet.Cells[current + startRow + 1, j + startColumn].Style.Font.Name, 1.66f);
  427. var measureText = graphics.MeasureString(properties[j].GetValue(item).ToString(), font);
  428. sheet.Column(j + startColumn).Width = Math.Min(110, Math.Max(measureText.Width, sheet.Column(j + startColumn).Width));
  429. }
  430. break;
  431. }
  432. }
  433. }
  434. current++;
  435. }
  436. sheet.Cells.AutoFitColumns(); // 表头自适应列宽
  437. sheet.Cells.Style.WrapText = true;
  438. }
  439. else
  440. {
  441. sheet.Cells[startRow, startColumn].LoadFromCollection(table, true, TableStyles.Light15).AutoFitColumns(12, 90);
  442. sheet.Cells.Style.WrapText = true;
  443. }
  444. }
  445. private static readonly NumberFormater NumberFormater = new("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1);
  446. /// <summary>
  447. /// 获取字母列
  448. /// </summary>
  449. /// <param name="sheet"></param>
  450. /// <param name="index"></param>
  451. /// <returns></returns>
  452. public static ExcelColumn Column(this ExcelWorksheet sheet, string index)
  453. {
  454. return sheet.Column((int)NumberFormater.FromString(index));
  455. }
  456. }