ExcelExtension.cs 25 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. if (hasPicColumn)
  161. {
  162. // 填充表头
  163. var maxWidth = new int[table.Columns.Count];
  164. for (var j = 0; j < table.Columns.Count; j++)
  165. {
  166. sheet.SetValue(startRow, j + startColumn, table.Columns[j].ColumnName);
  167. maxWidth[j] = Encoding.UTF8.GetBytes(table.Columns[j].ColumnName).Length;
  168. }
  169. sheet.Row(startRow).Style.Font.Bold = true; // 表头设置为粗体
  170. sheet.Row(startRow).Style.Font.Size = sheet.Row(startRow).Style.Font.Size * 1.11f; // 表头字号放大1.11倍
  171. sheet.Row(startRow).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
  172. sheet.Row(startRow).CustomHeight = true; // 自动调整行高
  173. if (settings != null)
  174. {
  175. foreach (var x in settings.ColumnTypes)
  176. {
  177. sheet.Column(x.Key).Style.Numberformat.Format = x.Value;
  178. }
  179. }
  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. var pictureType = ImageDetector.GetPictureType(s) ?? throw new ArgumentException($"{i}行{j}列图像格式不受支持");
  193. var bmp = new ExcelImage(s, pictureType).Bounds;
  194. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), s, pictureType);
  195. picture.SetPosition(i + startRow, 3, j + startColumn - 1, 5); //设置图片显示位置
  196. var percent = Math.Round(Math.Min(12000f / bmp.Height, 100));
  197. picture.SetSize((int)percent);
  198. sheet.Row(i + startRow + 1).Height = 90;
  199. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, bmp.Width * percent / 400);
  200. }
  201. sheet.SetValue(i + startRow + 1, j + startColumn, "");
  202. break;
  203. }
  204. case IEnumerable<Stream> streams:
  205. {
  206. double sumWidth = 0;
  207. foreach (var stream in streams.Where(stream => stream.Length > 2))
  208. {
  209. var pictureType = ImageDetector.GetPictureType(stream) ?? throw new ArgumentException($"{i}行{j}列图像格式不受支持");
  210. var bmp = new ExcelImage(stream, pictureType).Bounds;
  211. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), stream, pictureType);
  212. picture.SetPosition(i + startRow, 3, j + startColumn - 1, (int)Math.Ceiling(5 + sumWidth)); //设置图片显示位置
  213. var percent = Math.Min(12000f / bmp.Height, 100);
  214. picture.SetSize((int)percent);
  215. sheet.Row(i + startRow + 1).Height = 90;
  216. sumWidth += bmp.Width * percent / 100 + 5;
  217. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, sumWidth / 5);
  218. }
  219. sheet.SetValue(i + startRow + 1, j + startColumn, "");
  220. break;
  221. }
  222. case IDictionary<string, Stream> dic:
  223. {
  224. double sumWidth = 0;
  225. foreach (var kv in dic.Where(kv => kv.Value.Length > 2))
  226. {
  227. var pictureType = ImageDetector.GetPictureType(kv.Value) ?? throw new ArgumentException($"{i}行{j}列图像格式不受支持");
  228. var bmp = new ExcelImage(kv.Value, pictureType).Bounds;
  229. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), kv.Value, pictureType, new Uri(kv.Key));
  230. picture.SetPosition(i + startRow, 3, j + startColumn - 1, (int)Math.Ceiling(5 + sumWidth)); //设置图片显示位置
  231. var percent = Math.Min(12000f / bmp.Height, 100);
  232. picture.SetSize((int)percent);
  233. sheet.Row(i + startRow + 1).Height = 90;
  234. sumWidth += bmp.Width * percent / 100 + 5;
  235. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, sumWidth / 5);
  236. }
  237. sheet.SetValue(i + startRow + 1, j + startColumn, "");
  238. break;
  239. }
  240. case IDictionary<string, MemoryStream> dic:
  241. {
  242. double sumWidth = 0;
  243. foreach (var kv in dic.Where(kv => kv.Value.Length > 2))
  244. {
  245. var pictureType = ImageDetector.GetPictureType(kv.Value) ?? throw new ArgumentException($"{i}行{j}列图像格式不受支持");
  246. var bmp = new ExcelImage(kv.Value, pictureType).Bounds;
  247. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), kv.Value, pictureType, new Uri(kv.Key));
  248. picture.SetPosition(i + startRow, 3, j + startColumn - 1, (int)Math.Ceiling(5 + sumWidth)); //设置图片显示位置
  249. var percent = Math.Min(12000f / bmp.Height, 100);
  250. picture.SetSize((int)percent);
  251. sheet.Row(i + startRow + 1).Height = 90;
  252. sumWidth += bmp.Width * percent / 100 + 5;
  253. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, sumWidth / 5);
  254. }
  255. sheet.SetValue(i + startRow + 1, j + startColumn, "");
  256. break;
  257. }
  258. default:
  259. {
  260. sheet.SetValue(i + startRow + 1, j + startColumn, table.Rows[i][j] ?? "");
  261. if (table.Rows[i][j] is ValueType)
  262. {
  263. sheet.Column(j + startColumn).AutoFit();
  264. }
  265. else
  266. {
  267. // 根据单元格内容长度来自适应调整列宽
  268. using var bitmap = new Bitmap(1, 1);
  269. using var graphics = Graphics.FromImage(bitmap);
  270. using var font = new Font(sheet.Cells[i + startRow + 1, j + startColumn].Style.Font.Name, 1.66f);
  271. var measureText = graphics.MeasureString(table.Rows[i][j].ToString(), font);
  272. sheet.Column(j + startColumn).Width = Math.Min(110, Math.Max(measureText.Width, sheet.Column(j + startColumn).Width));
  273. }
  274. break;
  275. }
  276. }
  277. }
  278. }
  279. sheet.Cells.AutoFitColumns(); // 表头自适应列宽
  280. sheet.Cells.Style.WrapText = true;
  281. }
  282. else
  283. {
  284. sheet.Cells[startRow, startColumn].LoadFromDataTable(table, true, TableStyles.Light15).AutoFitColumns(12, 90);
  285. sheet.Cells.Style.WrapText = true;
  286. }
  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. if (hasPicColumn)
  315. {
  316. // 填充表头
  317. var maxWidth = new int[properties.Length];
  318. for (var j = 0; j < properties.Length; j++)
  319. {
  320. sheet.SetValue(startRow, j + startColumn, properties[j].Name);
  321. maxWidth[j] = Encoding.UTF8.GetBytes(properties[j].Name).Length;
  322. }
  323. sheet.Row(startRow).Style.Font.Bold = true; // 表头设置为粗体
  324. sheet.Row(startRow).Style.Font.Size = sheet.Row(startRow).Style.Font.Size * 1.11f; // 表头字号放大1.11倍
  325. sheet.Row(startRow).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
  326. sheet.Row(startRow).CustomHeight = true; // 自动调整行高
  327. if (settings != null)
  328. {
  329. foreach (var x in settings.ColumnTypes)
  330. {
  331. sheet.Column(x.Key).Style.Numberformat.Format = x.Value;
  332. }
  333. }
  334. // 填充内容
  335. int current = 0;
  336. foreach (var item in table)
  337. {
  338. sheet.Row(current + startRow + 1).CustomHeight = true; // 自动调整行高
  339. for (int j = 0; j < properties.Length; j++)
  340. {
  341. switch (properties[j].GetValue(item))
  342. {
  343. case Stream s:
  344. {
  345. if (s.Length > 2)
  346. {
  347. var pictureType = ImageDetector.GetPictureType(s) ?? throw new ArgumentException($"{current}行{j}列图像格式不受支持");
  348. var bmp = new ExcelImage(s, pictureType).Bounds;
  349. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), s, pictureType);
  350. picture.SetPosition(current + startRow, 3, j + startColumn - 1, 5); //设置图片显示位置
  351. var percent = Math.Round(Math.Min(12000f / bmp.Height, 100));
  352. picture.SetSize((int)percent);
  353. sheet.Row(current + startRow + 1).Height = 90;
  354. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, bmp.Width * percent / 400);
  355. }
  356. sheet.SetValue(current + startRow + 1, j + startColumn, "");
  357. break;
  358. }
  359. case IEnumerable<Stream> streams:
  360. {
  361. double sumWidth = 0;
  362. foreach (var stream in streams.Where(stream => stream.Length > 2))
  363. {
  364. var pictureType = ImageDetector.GetPictureType(stream) ?? throw new ArgumentException($"{current}行{j}列图像格式不受支持");
  365. var bmp = new ExcelImage(stream, pictureType).Bounds;
  366. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), stream, pictureType);
  367. picture.SetPosition(current + startRow, 3, j + startColumn - 1, (int)Math.Ceiling(5 + sumWidth)); //设置图片显示位置
  368. var percent = Math.Min(12000f / bmp.Height, 100);
  369. picture.SetSize((int)percent);
  370. sheet.Row(current + startRow + 1).Height = 90;
  371. sumWidth += bmp.Width * percent / 100 + 5;
  372. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, sumWidth / 5);
  373. }
  374. sheet.SetValue(current + startRow + 1, j + startColumn, "");
  375. break;
  376. }
  377. case IDictionary<string, Stream> dic:
  378. {
  379. double sumWidth = 0;
  380. foreach (var kv in dic.Where(kv => kv.Value.Length > 2))
  381. {
  382. var pictureType = ImageDetector.GetPictureType(kv.Value) ?? throw new ArgumentException($"{current}行{j}列图像格式不受支持");
  383. var bmp = new ExcelImage(kv.Value, pictureType).Bounds;
  384. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), kv.Value, pictureType, new Uri(kv.Key));
  385. picture.SetPosition(current + startRow, 3, j + startColumn - 1, (int)Math.Ceiling(5 + sumWidth)); //设置图片显示位置
  386. var percent = Math.Min(12000f / bmp.Height, 100);
  387. picture.SetSize((int)percent);
  388. sheet.Row(current + startRow + 1).Height = 90;
  389. sumWidth += bmp.Width * percent / 100 + 5;
  390. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, sumWidth / 5);
  391. }
  392. sheet.SetValue(current + startRow + 1, j + startColumn, "");
  393. break;
  394. }
  395. case IDictionary<string, MemoryStream> dic:
  396. {
  397. double sumWidth = 0;
  398. foreach (var kv in dic.Where(kv => kv.Value.Length > 2))
  399. {
  400. var pictureType = ImageDetector.GetPictureType(kv.Value) ?? throw new ArgumentException($"{current}行{j}列图像格式不受支持");
  401. var bmp = new ExcelImage(kv.Value, pictureType).Bounds;
  402. var picture = sheet.Drawings.AddPicture(Guid.NewGuid().ToString(), kv.Value, pictureType, new Uri(kv.Key));
  403. picture.SetPosition(current + startRow, 3, j + startColumn - 1, (int)Math.Ceiling(5 + sumWidth)); //设置图片显示位置
  404. var percent = Math.Min(12000f / bmp.Height, 100);
  405. picture.SetSize((int)percent);
  406. sheet.Row(current + startRow + 1).Height = 90;
  407. sumWidth += bmp.Width * percent / 100 + 5;
  408. sheet.Column(j + startColumn).Width = Math.Max(sheet.Column(j + startColumn).Width, sumWidth / 5);
  409. }
  410. sheet.SetValue(current + startRow + 1, j + startColumn, "");
  411. break;
  412. }
  413. default:
  414. {
  415. sheet.SetValue(current + startRow + 1, j + startColumn, properties[j].GetValue(item) ?? "");
  416. if (properties[j].GetValue(item) is ValueType)
  417. {
  418. sheet.Column(j + startColumn).AutoFit();
  419. }
  420. else
  421. {
  422. // 根据单元格内容长度来自适应调整列宽
  423. using var bitmap = new Bitmap(1, 1);
  424. using var graphics = Graphics.FromImage(bitmap);
  425. using var font = new Font(sheet.Cells[current + startRow + 1, j + startColumn].Style.Font.Name, 1.66f);
  426. var measureText = graphics.MeasureString(properties[j].GetValue(item).ToString(), font);
  427. sheet.Column(j + startColumn).Width = Math.Min(110, Math.Max(measureText.Width, sheet.Column(j + startColumn).Width));
  428. }
  429. break;
  430. }
  431. }
  432. }
  433. current++;
  434. }
  435. sheet.Cells.AutoFitColumns(); // 表头自适应列宽
  436. sheet.Cells.Style.WrapText = true;
  437. }
  438. else
  439. {
  440. sheet.Cells[startRow, startColumn].LoadFromCollection(table, true, TableStyles.Light15).AutoFitColumns(12, 90);
  441. sheet.Cells.Style.WrapText = true;
  442. }
  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. }