ExportExcelService.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. using NPOI.HSSF.UserModel;
  2. using NPOI.SS.UserModel;
  3. using NPOI.SS.Util;
  4. using NPOI.XSSF.UserModel;
  5. namespace YBEE.EQM.Application;
  6. /// <summary>
  7. /// EXCEL导出服务
  8. /// </summary>
  9. public class ExportExcelService : IExportExcelService, ISingleton
  10. {
  11. /// <summary>
  12. /// 导出 Excel 文件
  13. /// </summary>
  14. /// <typeparam name="T"></typeparam>
  15. /// <param name="input"></param>
  16. /// <returns></returns>
  17. public byte[] ExportExcel<T>(ExportExcelDto<T> input)
  18. {
  19. IWorkbook wb = new XSSFWorkbook();
  20. ISheet sheet = wb.CreateSheet();
  21. sheet.DisplayGridlines = false;
  22. input.SetSheet?.Invoke(sheet);
  23. var cellStyle = GetCellStyle(wb, input.FontSize, input.TitleFontSize);
  24. // 行索引号
  25. int rowNum = 0;
  26. #region 标题
  27. IRow titleRow = sheet.CreateRow(rowNum++);
  28. titleRow.Height = input.TitleHeight ?? ExportExcelCellStyle.DefaultTitleHeight;
  29. AddCell(input.Title, titleRow, 0, cellStyle.TitleStyle, sheet);
  30. sheet.AddMergedRegion(new CellRangeAddress(rowNum - 1, rowNum - 1, 0, input.Columns.Count - 1));
  31. #endregion
  32. #region 摘要
  33. int freezeRowCount = 1;
  34. if (input.BuildSummary == null)
  35. {
  36. string summary = "";
  37. if (input.IncludeExportTime) { summary = $"导出时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss} "; };
  38. if (!(string.IsNullOrEmpty(input.Summary) || string.IsNullOrWhiteSpace(input.Summary))) { summary = $"{summary}{input.Summary}"; }
  39. if (summary != "")
  40. {
  41. IRow summaryRow = sheet.CreateRow(rowNum++);
  42. summaryRow.Height = ExportExcelCellStyle.DefaultRowHeight;
  43. AddCell(summary, summaryRow, 0, cellStyle.SummaryStyle, sheet);
  44. sheet.AddMergedRegion(new CellRangeAddress(rowNum - 1, rowNum - 1, 0, input.Columns.Count - 1));
  45. freezeRowCount++;
  46. }
  47. }
  48. else
  49. {
  50. int rc = input.BuildSummary(sheet, cellStyle, rowNum);
  51. freezeRowCount += rc;
  52. rowNum += rc;
  53. }
  54. #endregion
  55. #region 列头
  56. IRow headerRow = sheet.CreateRow(rowNum++);
  57. headerRow.Height = input.HeaderHeight;
  58. for (int i = 0; i < input.Columns.Count; i++)
  59. {
  60. var col = input.Columns[i];
  61. AddCell(col.Name, headerRow, i, cellStyle.ColumnHeaderStyle, sheet, col.Width);
  62. }
  63. sheet.CreateFreezePane(0, ++freezeRowCount);
  64. #endregion
  65. #region 数据
  66. foreach (var item in input.Items)
  67. {
  68. IRow row = sheet.CreateRow(rowNum++);
  69. row.Height = input.RowHeight ?? ExportExcelCellStyle.DefaultRowHeight;
  70. for (int i = 0; i < input.Columns.Count; i++)
  71. {
  72. var col = input.Columns[i];
  73. ICellStyle cstyle = cellStyle.CenterCellStyle;
  74. switch (col.Align)
  75. {
  76. case ExportExcelCellAlign.LEFT:
  77. cstyle = cellStyle.LeftCellStyle;
  78. break;
  79. case ExportExcelCellAlign.RIGHT:
  80. cstyle = cellStyle.RightCellStyle;
  81. break;
  82. }
  83. AddCell(col.GetCellValue(item), row, i, cstyle, sheet, col.Width);
  84. }
  85. }
  86. #endregion
  87. MemoryStream ms = new();
  88. wb.Write(ms, false);
  89. ms.Flush();
  90. return ms.ToArray();
  91. }
  92. #region 静态方法
  93. /// <summary>
  94. /// 获取单元格表头和单元格样式
  95. /// </summary>
  96. /// <param name="wb"></param>
  97. /// <param name="fontSize">正文字体大小</param>
  98. /// <param name="titleFontSize">标题字体大小</param>
  99. /// <returns></returns>
  100. public ExportExcelCellStyle GetCellStyle(IWorkbook wb, double fontSize = 10, double titleFontSize = 16)
  101. {
  102. ExportExcelCellStyle cellStyle = new()
  103. {
  104. TitleStyle = wb.CreateCellStyle(),
  105. SummaryStyle = wb.CreateCellStyle(),
  106. ColumnHeaderStyle = wb.CreateCellStyle(),
  107. CenterCellStyle = wb.CreateCellStyle(),
  108. LeftCellStyle = wb.CreateCellStyle(),
  109. RightCellStyle = wb.CreateCellStyle(),
  110. FillCellStyle = wb.CreateCellStyle(),
  111. };
  112. // 标题样式
  113. cellStyle.TitleStyle.Alignment = HorizontalAlignment.Center;
  114. cellStyle.TitleStyle.VerticalAlignment = VerticalAlignment.Center;
  115. IFont titleFont = wb.CreateFont();
  116. titleFont.IsBold = true;
  117. titleFont.FontName = cellStyle.TitleFontName;
  118. titleFont.FontHeightInPoints = titleFontSize;
  119. cellStyle.TitleStyle.SetFont(titleFont);
  120. // 摘要样式
  121. cellStyle.SummaryStyle.Alignment = HorizontalAlignment.Left;
  122. cellStyle.SummaryStyle.VerticalAlignment = VerticalAlignment.Center;
  123. IFont summaryFont = wb.CreateFont();
  124. summaryFont.FontName = cellStyle.FontName;
  125. summaryFont.FontHeightInPoints = fontSize;
  126. cellStyle.SummaryStyle.SetFont(summaryFont);
  127. // 列头样式
  128. cellStyle.ColumnHeaderStyle = wb.CreateCellStyle();
  129. cellStyle.ColumnHeaderStyle.Alignment = HorizontalAlignment.Center;
  130. cellStyle.ColumnHeaderStyle.VerticalAlignment = VerticalAlignment.Center;
  131. cellStyle.ColumnHeaderStyle.BorderTop = BorderStyle.Thin;
  132. cellStyle.ColumnHeaderStyle.BorderLeft = BorderStyle.Thin;
  133. cellStyle.ColumnHeaderStyle.BorderRight = BorderStyle.Thin;
  134. cellStyle.ColumnHeaderStyle.BorderBottom = BorderStyle.Thin;
  135. cellStyle.ColumnHeaderStyle.WrapText = true;
  136. IFont headerFont = wb.CreateFont();
  137. headerFont.IsBold = true;
  138. headerFont.FontName = cellStyle.TitleFontName;
  139. headerFont.FontHeightInPoints = fontSize;
  140. cellStyle.ColumnHeaderStyle.SetFont(headerFont);
  141. // 默认居中样式
  142. cellStyle.CenterCellStyle = wb.CreateCellStyle();
  143. cellStyle.CenterCellStyle.Alignment = HorizontalAlignment.Center;
  144. cellStyle.CenterCellStyle.VerticalAlignment = VerticalAlignment.Center;
  145. cellStyle.CenterCellStyle.BorderTop = BorderStyle.Thin;
  146. cellStyle.CenterCellStyle.BorderLeft = BorderStyle.Thin;
  147. cellStyle.CenterCellStyle.BorderRight = BorderStyle.Thin;
  148. cellStyle.CenterCellStyle.BorderBottom = BorderStyle.Thin;
  149. cellStyle.CenterCellStyle.WrapText = true;
  150. IFont cellFont = wb.CreateFont();
  151. cellFont.FontName = cellStyle.FontName;
  152. cellFont.FontHeightInPoints = fontSize;
  153. cellStyle.CenterCellStyle.SetFont(cellFont);
  154. // 居左样式
  155. cellStyle.LeftCellStyle = wb.CreateCellStyle();
  156. cellStyle.LeftCellStyle.CloneStyleFrom(cellStyle.CenterCellStyle);
  157. cellStyle.LeftCellStyle.Alignment = HorizontalAlignment.Left;
  158. // 居右样式
  159. cellStyle.RightCellStyle = wb.CreateCellStyle();
  160. cellStyle.RightCellStyle.CloneStyleFrom(cellStyle.CenterCellStyle);
  161. cellStyle.RightCellStyle.Alignment = HorizontalAlignment.Right;
  162. // 背景样式
  163. cellStyle.FillCellStyle = wb.CreateCellStyle();
  164. cellStyle.FillCellStyle.CloneStyleFrom(cellStyle.CenterCellStyle);
  165. if (wb.SpreadsheetVersion.DefaultExtension == "xls")
  166. {
  167. HSSFPalette palette = ((HSSFWorkbook)wb).GetCustomPalette();
  168. palette.SetColorAtIndex(48, 245, 245, 245);
  169. cellStyle.FillCellStyle.FillForegroundColor = palette.FindColor(245, 245, 245).Indexed;
  170. }
  171. else
  172. {
  173. cellStyle.FillCellStyle.FillForegroundColor = 0;
  174. cellStyle.FillCellStyle.FillPattern = FillPattern.SolidForeground;
  175. ((XSSFColor)cellStyle.FillCellStyle.FillForegroundColorColor).SetRgb(new byte[] { 245, 245, 245 });
  176. }
  177. return cellStyle;
  178. }
  179. /// <summary>
  180. /// 添加单元格
  181. /// </summary>
  182. /// <param name="value"></param>
  183. /// <param name="row"></param>
  184. /// <param name="columnIndex"></param>
  185. /// <param name="cellStyle"></param>
  186. /// <param name="sheet"></param>
  187. /// <param name="width"></param>
  188. public void AddCell(object value, IRow row, int columnIndex, ICellStyle cellStyle, ISheet sheet = null, int? width = 8)
  189. {
  190. ICell cell = row.CreateCell(columnIndex);
  191. cell.CellStyle = cellStyle;
  192. if (value != null)
  193. {
  194. var valueTypeName = value.GetType().Name;
  195. if (valueTypeName.Contains("Int") || valueTypeName == "Double" || valueTypeName == "Decimal")
  196. {
  197. cell.SetCellValue(Convert.ToDouble(value));
  198. }
  199. else if (valueTypeName == "String")
  200. {
  201. cell.SetCellValue(value.ToString());
  202. }
  203. else if (valueTypeName == "Boolean")
  204. {
  205. cell.SetCellValue((bool)value);
  206. }
  207. }
  208. if (sheet != null && width.HasValue)
  209. {
  210. sheet.SetColumnWidth(columnIndex, width.Value * 256);
  211. }
  212. }
  213. #endregion
  214. }