ExcelExtension.cs 20 KB

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