1
1

ExcelExtension.cs 34 KB

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