using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using Kreta.Core.ConnectionType; using Kreta.Resources; using OfficeOpenXml; using OfficeOpenXml.Style; namespace Kreta.BusinessLogic.Helpers.Nyomtatvanyok.Excel { public abstract class BaseNyomtatvanyExcel : IDisposable { private const string ConstFontName = "Calibri"; protected class CellStyle { public string Name { get; set; } /// integer (not really needed unless you need to round numbers, Excel with use default cell properties) --> "0" /// integer without displaying the number 0 in the cell --> "#" /// number with 1 decimal place --> "0.0" /// number with 2 decimal places --> "0.00" /// number with 2 decimal places and thousand separator --> "#,##0.00" /// number with 2 decimal places and thousand separator and money symbol --> "€#,##0.00" /// percentage (1 = 100%, 0.01 = 1%) --> "0%" public string Numberformat { get; set; } = "0"; public string BgColorHex { get; set; } = "transparent"; public bool FontBold { get; set; } public int FontSize { get; set; } = 11; public string FontName { get; set; } = ConstFontName; public string FontColorHex { get; set; } = "automatic"; public int TextRotation { get; set; } public bool WrapText { get; set; } public ExcelBorderStyle LeftBorder { get; set; } = ExcelBorderStyle.None; public ExcelBorderStyle RightBorder { get; set; } = ExcelBorderStyle.None; public ExcelBorderStyle TopBorder { get; set; } = ExcelBorderStyle.None; public ExcelBorderStyle BottomBorder { get; set; } = ExcelBorderStyle.None; public ExcelHorizontalAlignment HorizontalAlignment { get; set; } = ExcelHorizontalAlignment.Left; public ExcelVerticalAlignment VerticalAlignment { get; set; } = ExcelVerticalAlignment.Center; public CellStyle() { } public CellStyle(string Name) { this.Name = Name; } public CellStyle(BaseNyomtatvanyExcel.CellStyle prevCellStyle) { Numberformat = prevCellStyle.Numberformat; BgColorHex = prevCellStyle.BgColorHex; FontBold = prevCellStyle.FontBold; FontSize = prevCellStyle.FontSize; FontName = prevCellStyle.FontName; FontColorHex = prevCellStyle.FontColorHex; TextRotation = prevCellStyle.TextRotation; WrapText = prevCellStyle.WrapText; LeftBorder = prevCellStyle.LeftBorder; RightBorder = prevCellStyle.RightBorder; TopBorder = prevCellStyle.TopBorder; BottomBorder = prevCellStyle.BottomBorder; HorizontalAlignment = prevCellStyle.HorizontalAlignment; VerticalAlignment = prevCellStyle.VerticalAlignment; } } protected string Author = ""; protected ExcelPackage ExcelPackage; protected DataSet DataSet; protected string StoredProcedure = null; protected Dictionary DbParameters = new Dictionary(); protected Dictionary NamedCellStyles = new Dictionary(); protected CellStyle NormalStyle = null; protected CellStyle NormalStyleWrapText = null; protected CellStyle HeaderStyle = null; protected CellStyle HeaderStyle90 = null; protected CellStyle IntegerStyle = null; protected CellStyle IntegerBoldStyle = null; protected CellStyle Numeric2Style = null; protected CellStyle Numeric2BoldStyle = null; protected CellStyle NormalStyleBottomBordered = null; protected CellStyle NormalStyleCentered = null; protected CellStyle HeaderStyleBottomBordered = null; protected CellStyle HeaderStyle90BottomBordered = null; protected CellStyle IntegerStyleBottomBordered = null; protected CellStyle IntegerBoldStyleBottomBordered = null; protected CellStyle Numeric2StyleBottomBordered = null; protected CellStyle Numeric2BoldStyleBottomBordered = null; protected CellStyle HeaderStyleBottomBorderedBGGray = null; protected CellStyle HeaderStyle90BottomBorderedBGGray = null; protected CellStyle DocnameStyle = null; protected CellStyle DocheaderStyle1 = null; protected CellStyle DocheaderStyle2 = null; protected CellStyle DocheaderStyleSideBordered = null; protected CellStyle DocheaderStyleMergedUpperCell = null; protected CellStyle DocheaderStyleMergedLowerCell = null; protected CellStyle DocheaderStyleCenteredWithoutBorder = null; protected CellStyle Numeric2BoldBigerStyleBottomBordered = null; protected CellStyle PercentStyleBottomBordered = null; protected CellStyle PercentBoldStyleBottomBordered = null; protected bool isMultisheetExcel; private IConnectionType _connectionType; public DataSet GetSheetDataSet() => DataSet; protected BaseNyomtatvanyExcel(IConnectionType connectionType, bool isMultisheetExcel = false) { _connectionType = connectionType; this.isMultisheetExcel = isMultisheetExcel; NamedCellStyles.Add("NormalStyle", NormalStyle = new CellStyle("NormalStyle")); NamedCellStyles.Add("NormalStyleWrapText", NormalStyleWrapText = new CellStyle(NamedCellStyles["NormalStyle"]) { Name = "NormalStyleWrapText", WrapText = true }); NamedCellStyles.Add("HeaderStyle", HeaderStyle = new CellStyle("HeaderStyle") { FontBold = true, WrapText = true }); NamedCellStyles.Add("HeaderStyle90", HeaderStyle90 = new CellStyle(NamedCellStyles["HeaderStyle"]) { Name = "HeaderStyle90", TextRotation = 90, HorizontalAlignment = ExcelHorizontalAlignment.Center, VerticalAlignment = ExcelVerticalAlignment.Bottom }); NamedCellStyles.Add("IntegerStyle", IntegerStyle = new CellStyle("IntegerStyle") { Numberformat = "0", HorizontalAlignment = ExcelHorizontalAlignment.Center }); NamedCellStyles.Add("IntegerBoldStyle", IntegerBoldStyle = new CellStyle(NamedCellStyles["IntegerStyle"]) { Name = "IntegerBoldStyle", FontBold = true }); NamedCellStyles.Add("Numeric2Style", Numeric2Style = new CellStyle("Numeric2Style") { Numberformat = "0.00", HorizontalAlignment = ExcelHorizontalAlignment.Center }); NamedCellStyles.Add("Numeric2BoldStyle", Numeric2BoldStyle = new CellStyle(NamedCellStyles["Numeric2Style"]) { Name = "Numeric2BoldStyle", FontBold = true }); NamedCellStyles.Add("NormalStyleBottomBordered", NormalStyleBottomBordered = new CellStyle("NormalStyleBottomBordered") { TopBorder = ExcelBorderStyle.None, LeftBorder = ExcelBorderStyle.None, BottomBorder = ExcelBorderStyle.Thin, RightBorder = ExcelBorderStyle.None, }); NamedCellStyles.Add("NormalStyleCentered", NormalStyleCentered = new CellStyle("NormalStyleCentered") { HorizontalAlignment = ExcelHorizontalAlignment.Center, VerticalAlignment = ExcelVerticalAlignment.Center, WrapText = true }); NamedCellStyles.Add("HeaderStyleBottomBordered", HeaderStyleBottomBordered = new CellStyle(NamedCellStyles["NormalStyleBottomBordered"]) { Name = "HeaderStyleBottomBordered", FontBold = true, WrapText = true }); NamedCellStyles.Add("HeaderStyle90BottomBordered", HeaderStyle90BottomBordered = new CellStyle(NamedCellStyles["HeaderStyleBottomBordered"]) { Name = "HeaderStyle90BottomBordered", TextRotation = 90, HorizontalAlignment = ExcelHorizontalAlignment.Center, VerticalAlignment = ExcelVerticalAlignment.Bottom }); NamedCellStyles.Add("IntegerStyleBottomBordered", IntegerStyleBottomBordered = new CellStyle(NamedCellStyles["NormalStyleBottomBordered"]) { Name = "IntegerStyleBottomBordered", Numberformat = "0", HorizontalAlignment = ExcelHorizontalAlignment.Center }); NamedCellStyles.Add("IntegerBoldStyleBottomBordered", IntegerBoldStyleBottomBordered = new CellStyle(NamedCellStyles["IntegerStyleBottomBordered"]) { Name = "IntegerBoldStyleBottomBordered", FontBold = true }); NamedCellStyles.Add("Numeric2StyleBottomBordered", Numeric2StyleBottomBordered = new CellStyle(NamedCellStyles["NormalStyleBottomBordered"]) { Name = "Numeric2StyleBottomBordered", Numberformat = "0.00", HorizontalAlignment = ExcelHorizontalAlignment.Center }); NamedCellStyles.Add("Numeric2BoldStyleBottomBordered", Numeric2BoldStyleBottomBordered = new CellStyle(NamedCellStyles["Numeric2StyleBottomBordered"]) { Name = "Numeric2BoldStyleBottomBordered", FontBold = true }); NamedCellStyles.Add("HeaderStyleBottomBorderedBGGray", HeaderStyleBottomBorderedBGGray = new CellStyle(NamedCellStyles["HeaderStyleBottomBordered"]) { Name = "HeaderStyleBottomBorderedBGGray", BgColorHex = "#AAAAAA" }); NamedCellStyles.Add("HeaderStyle90BottomBorderedBGGray", HeaderStyle90BottomBorderedBGGray = new CellStyle(NamedCellStyles["HeaderStyle90BottomBordered"]) { Name = "HeaderStyle90BottomBorderedBGGray", BgColorHex = "#AAAAAA" }); NamedCellStyles.Add("DocnameStyle", DocnameStyle = new CellStyle(NamedCellStyles["HeaderStyle"]) { Name = "DocnameStyle", FontSize = 16 }); NamedCellStyles.Add("DocheaderStyle1", DocheaderStyle1 = new CellStyle(NamedCellStyles["HeaderStyle"]) { Name = "DocheaderStyle1", FontColorHex = "#FFFFFF", BgColorHex = "#18A0C8", HorizontalAlignment = ExcelHorizontalAlignment.Left, VerticalAlignment = ExcelVerticalAlignment.Center }); NamedCellStyles.Add("DocheaderStyleSideBordered", DocheaderStyleSideBordered = new CellStyle(NamedCellStyles["HeaderStyle"]) { Name = "DocheaderStyleSideBordered", FontColorHex = "#FFFFFF", BgColorHex = "#18A0C8", HorizontalAlignment = ExcelHorizontalAlignment.Center, VerticalAlignment = ExcelVerticalAlignment.Center, LeftBorder = ExcelBorderStyle.Thin, RightBorder = ExcelBorderStyle.Thin, BottomBorder = ExcelBorderStyle.Thin }); NamedCellStyles.Add("DocheaderStyleMergedUpperCell", DocheaderStyleMergedUpperCell = new CellStyle(NamedCellStyles["HeaderStyle"]) { Name = "DocheaderStyleMergedUpperCell", FontColorHex = "#FFFFFF", BgColorHex = "#18A0C8", HorizontalAlignment = ExcelHorizontalAlignment.Left, VerticalAlignment = ExcelVerticalAlignment.Center, TopBorder = ExcelBorderStyle.Thin, LeftBorder = ExcelBorderStyle.Thin, RightBorder = ExcelBorderStyle.Thin }); NamedCellStyles.Add("DocheaderStyleMergedLowerCell", DocheaderStyleMergedLowerCell = new CellStyle(NamedCellStyles["HeaderStyle"]) { Name = "DocheaderStyleMergedLowerCell", HorizontalAlignment = ExcelHorizontalAlignment.Left, VerticalAlignment = ExcelVerticalAlignment.Center, LeftBorder = ExcelBorderStyle.Thin, RightBorder = ExcelBorderStyle.Thin, BottomBorder = ExcelBorderStyle.Thin }); NamedCellStyles.Add("DocheaderStyleCenteredWithoutBorder", DocheaderStyleCenteredWithoutBorder = new CellStyle(NamedCellStyles["DocheaderStyle1"]) { Name = "DocheaderStyleCenteredWithoutBorder", HorizontalAlignment = ExcelHorizontalAlignment.Center, VerticalAlignment = ExcelVerticalAlignment.Center, LeftBorder = ExcelBorderStyle.None, RightBorder = ExcelBorderStyle.None, TopBorder = ExcelBorderStyle.None, BottomBorder = ExcelBorderStyle.None }); NamedCellStyles.Add("DocheaderStyle2", DocheaderStyle2 = new CellStyle(NamedCellStyles["DocheaderStyle1"]) { Name = "DocheaderStyle2", BgColorHex = "#5D5D5D" }); NamedCellStyles.Add("Numeric2BoldBigerStyleBottomBordered", Numeric2BoldBigerStyleBottomBordered = new CellStyle(NamedCellStyles["Numeric2BoldStyleBottomBordered"]) { Name = "Numeric2BoldBigerStyleBottomBordered", FontSize = 14 }); NamedCellStyles.Add("PercentStyleBottomBordered", PercentStyleBottomBordered = new CellStyle(NamedCellStyles["NormalStyleBottomBordered"]) { Name = "PercentStyleBottomBordered", Numberformat = "0%", HorizontalAlignment = ExcelHorizontalAlignment.Center }); NamedCellStyles.Add("PercentBoldStyleBottomBordered", PercentBoldStyleBottomBordered = new CellStyle(NamedCellStyles["PercentStyleBottomBordered"]) { Name = "PercentBoldStyleBottomBordered", FontBold = true }); } protected DataTable CreateDataTable(List list) { var dataTable = new DataTable(); var firstRow = true; foreach (var listRow in list) { if (firstRow) { foreach (var hcol in listRow) dataTable.Columns.Add(hcol); firstRow = false; } else { int col = 0; var dataRow = dataTable.NewRow(); foreach (DataColumn dataColumn in dataTable.Columns) dataRow[dataColumn.ToString()] = listRow[col++]; dataTable.Rows.Add(dataRow); } } return dataTable; } protected void SetExcelDataSet(DataSet ds = null) { if (ds == null) { if (DbParameters == null || StoredProcedure == null) { throw new NullReferenceException("DB Parameterek nincsenek beallitva"); } DataSet = new NyomtatvanyokHelper(_connectionType).GetNyomtatvanyStoredProcedureDataSet(StoredProcedure, DbParameters); if (DataSet == null) { throw new NoNullAllowedException(StoredProcedure + " SP has no result!"); } } else { DataSet = ds; } } public abstract void CreateSheet(Dictionary dbParameters, int sheetIndex = 1); public MemoryStream ExcelNyomtatas() { return new MemoryStream(ExcelPackage.GetAsByteArray()); } public MemoryStream ExcelNyomtatas(Dictionary dbParameters) { if (!isMultisheetExcel) { if (dbParameters == null) { throw new ApplicationException("Egy lapos excel munkafüzet nyomtatásához az adatbázis paraméterek kötelezőek."); } if (ExcelPackage.Workbook.Worksheets.Count > 0) { GenerateNewExcelPackage(); SetWorkbookProperties(); } CreateSheet(dbParameters); } return ExcelNyomtatas(); } protected void SetWorkbookProperties() { ExcelPackage.Workbook.Properties.Author = ""; ExcelPackage.Workbook.Properties.Title = ""; ExcelPackage.Workbook.Properties.Company = ""; foreach (KeyValuePair style in NamedCellStyles) ChangeStyle(ExcelPackage.Workbook.Styles.CreateNamedStyle(style.Key), style.Value); } protected void AddNamedStyle(string styleName, CellStyle cellStyle) => ChangeStyle(ExcelPackage.Workbook.Styles.CreateNamedStyle(styleName), cellStyle); protected ExcelWorksheet CreateSheet(string sheetName, int position = 1, eOrientation orientation = eOrientation.Portrait, bool fitToPage = false, int fitToWidth = 1, int fitToHeight = 1, int fontSize = 11, string fontName = ConstFontName) { if (sheetName.Length > 31) { sheetName = sheetName.Substring(0, 31); } ExcelWorksheet worksheet = ExcelPackage.Workbook.Worksheets[sheetName]; if (worksheet == null) { worksheet = ExcelPackage.Workbook.Worksheets.Add(sheetName); worksheet.Cells.Style.Font.Size = fontSize; worksheet.Cells.Style.Font.Name = fontName; if (fitToPage) { worksheet.PrinterSettings.FitToPage = true; worksheet.PrinterSettings.FitToWidth = fitToWidth; worksheet.PrinterSettings.FitToHeight = fitToHeight; } worksheet.PrinterSettings.Orientation = orientation; } return worksheet; } public string ColumnLabel(int col) { var dividend = col; var columnLabel = string.Empty; while (dividend > 0) { var modulo = (dividend - 1) % 26; columnLabel = Convert.ToChar(65 + modulo) + columnLabel; dividend = (dividend - modulo) / 26; } return columnLabel; } protected void AddComment(ExcelWorksheet worksheet, int row, int col, string comment) { if (comment != null) { var commentCell = worksheet.Cells[row, col]; AddComment(commentCell, comment); } } protected void AddComment(ExcelRange cell, string comment) { if (!string.IsNullOrWhiteSpace(comment)) { cell.AddComment(comment, Author); cell.Comment.AutoFit = true; } } private ExcelRange AddValueCell(ExcelWorksheet worksheet, int row, int col, object value) { if (row < 1 || col < 1) return null; var cell = worksheet.Cells[row, col]; cell.Value = value; return cell; } private ExcelRange AddValueRange(ExcelWorksheet worksheet, int startRow, int startCol, int endRow, int endCol, object value) { if (startRow < 1 || startCol < 1 || endRow < 1 || endCol < 1) return null; var cell = worksheet.Cells[startRow, startCol, endRow, endCol]; cell.Value = value; worksheet.Cells[startRow, startCol, endRow, endCol].Merge = true; return cell; } private ExcelRange AddFormulaCell(ExcelWorksheet worksheet, int row, int col, string value) { if (row < 1 || col < 1) return null; worksheet.Workbook.CalcMode = ExcelCalcMode.Automatic; var cell = worksheet.Cells[row, col]; cell.Formula = value; return cell; } private ExcelRange AddFormulaRange(ExcelWorksheet worksheet, int startRow, int startCol, int endRow, int endCol, string value) { if (startRow < 1 || startCol < 1 || endRow < 1 || endCol < 1) return null; worksheet.Workbook.CalcMode = ExcelCalcMode.Automatic; var cell = worksheet.Cells[startRow, startCol, endRow, endCol]; cell.Formula = value; worksheet.Cells[startRow, startCol, endRow, endCol].Merge = true; return cell; } protected void AddTanuloAdatokFejlec(ExcelWorksheet worksheet, int fejlecRow) { var tanuloNevCell = worksheet.Cells[fejlecRow, 1]; tanuloNevCell.Value = TanuloResource.TanuloNeve; ChangeStyle(tanuloNevCell, HeaderStyleBottomBordered); var oktatasiAzonositoCell = worksheet.Cells[fejlecRow, 2]; oktatasiAzonositoCell.Value = TanuloResource.OktatasiAzonosito; ChangeStyle(oktatasiAzonositoCell, HeaderStyleBottomBordered); } private void ChangeStyle(ExcelRange cell, CellStyle cellStyle) => cell.StyleName = cellStyle.Name; private void ChangeStyle(OfficeOpenXml.Style.XmlAccess.ExcelNamedStyleXml excelNamedStyleXml, CellStyle cellStyle) { excelNamedStyleXml.Style.Numberformat.Format = cellStyle.Numberformat; excelNamedStyleXml.Style.Font.Bold = cellStyle.FontBold; excelNamedStyleXml.Style.TextRotation = cellStyle.TextRotation; excelNamedStyleXml.Style.HorizontalAlignment = cellStyle.HorizontalAlignment; excelNamedStyleXml.Style.VerticalAlignment = cellStyle.VerticalAlignment; excelNamedStyleXml.Style.WrapText = cellStyle.WrapText; var excelStyleBorder = excelNamedStyleXml.Style.Border; if (cellStyle.BottomBorder != ExcelBorderStyle.None) excelStyleBorder.Bottom.Style = cellStyle.BottomBorder; if (cellStyle.TopBorder != ExcelBorderStyle.None) excelStyleBorder.Top.Style = cellStyle.TopBorder; if (cellStyle.LeftBorder != ExcelBorderStyle.None) excelStyleBorder.Left.Style = cellStyle.LeftBorder; if (cellStyle.RightBorder != ExcelBorderStyle.None) excelStyleBorder.Right.Style = cellStyle.RightBorder; ChangeFontColor(excelNamedStyleXml.Style, cellStyle.FontColorHex); ChangeBgColor(excelNamedStyleXml.Style, cellStyle.BgColorHex); } private void ChangeFontColor(ExcelStyle excelStyle, string fontColorHex = "automatic") { if (fontColorHex?.Equals("automatic", StringComparison.OrdinalIgnoreCase) == false) excelStyle.Font.Color.SetColor(System.Drawing.ColorTranslator.FromHtml(fontColorHex)); } private void ChangeBgColor(ExcelStyle excelStyle, string bgColorHex = "transparent") { if (bgColorHex?.Equals("transparent", StringComparison.OrdinalIgnoreCase) == false) { excelStyle.Fill.PatternType = ExcelFillStyle.Solid; excelStyle.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml(bgColorHex)); } } private bool AddCellWithTypeCheck(ExcelWorksheet worksheet, int row, int col, object dtvalue, CellStyle cellStyle = null, string comment = null) { var aggregatedValues = true; switch (dtvalue) { case int _: case double _: AddNumberCell(worksheet, row, col, dtvalue, cellStyle, comment); break; case string _ when int.TryParse((string)dtvalue, out int intDtvalue): AddNumberCell(worksheet, row, col, intDtvalue, cellStyle, comment); break; case string _ when double.TryParse((string)dtvalue, out double doubleDtValue): AddNumberCell(worksheet, row, col, doubleDtValue, cellStyle, comment); break; default: AddLabelCell(worksheet, row, col, dtvalue.ToString(), cellStyle, comment); aggregatedValues = false; break; } return aggregatedValues; } protected void AddLabelCell(ExcelWorksheet worksheet, int row, int col, string value, CellStyle cellStyle = null, string comment = null) { var cell = AddValueCell(worksheet, row, col, value); ChangeStyle(cell, cellStyle ?? new CellStyle("NormalStyle")); AddComment(cell, comment); } protected void AddNumberCell(ExcelWorksheet worksheet, int row, int col, object value, CellStyle cellStyle = null, string comment = null) { var cell = AddValueCell(worksheet, row, col, value); ChangeStyle(cell, cellStyle ?? NamedCellStyles["IntegerStyle"]); AddComment(cell, comment); } protected void AddFormulaCell(ExcelWorksheet worksheet, int row, int col, string value, CellStyle cellStyle, string comment = null) { var cell = AddFormulaCell(worksheet, row, col, value); ChangeStyle(cell, cellStyle ?? NamedCellStyles["IntegerStyle"]); AddComment(cell, comment); } protected void AddAggregateFormulaCell(ExcelWorksheet worksheet, int row, int col, string aggrfunctionname, int startRow, int startCol, int endRow, int endCol, bool errorCheck = false, CellStyle cellStyle = null) { var aggregateCondition = ""; if (aggrfunctionname.StartsWith("COUNTIF")) { var rx = new System.Text.RegularExpressions.Regex("[,]"); var array = rx.Split(aggrfunctionname); aggrfunctionname = array[0]; aggregateCondition = "," + array[1]; } if (aggrfunctionname.StartsWith("IF")) { //IF,#=,#, var rx = new System.Text.RegularExpressions.Regex("[,]"); var array = rx.Split(aggrfunctionname); rx = new System.Text.RegularExpressions.Regex("="); var condarray = rx.Split(array[1]); var form = string.Format("{0}({1}{2}{3},{4}{5},{6})", array[0], ColumnLabel(col + int.Parse(condarray[0].Substring(1))), row, "=" + condarray[1], ColumnLabel(col + int.Parse(array[2].Substring(1))), row, array[3]); if (errorCheck) form = "IF(ISERROR(" + form + "),\"\"," + form + ")"; AddFormulaCell(worksheet, row, col, "=" + form, cellStyle); return; } string value = null; if (startCol <= endCol) { string formula = aggrfunctionname + "(" + ColumnLabel(startCol) + startRow + ":" + ColumnLabel(endCol) + endRow + aggregateCondition + ")"; if (errorCheck) { formula = "IF(ISERROR(" + formula + "),\"\"," + formula + ")"; } value = "=" + formula; } AddFormulaCell(worksheet, row, col, value, cellStyle); } protected void AddLabelRange(ExcelWorksheet worksheet, int startRow, int startCol, int endRow, int endCol, string value, CellStyle cellStyle = null, string comment = null) { var cell = AddValueRange(worksheet, startRow, startCol, endRow, endCol, value); ChangeStyle(cell, cellStyle ?? new CellStyle()); AddComment(cell, comment); } protected void AddNumberRange(ExcelWorksheet worksheet, int startRow, int startCol, int endRow, int endCol, object value, CellStyle cellStyle = null, string comment = null) { var cell = AddValueRange(worksheet, startRow, startCol, endRow, endCol, value); ChangeStyle(cell, cellStyle ?? NamedCellStyles["IntegerStyle"]); AddComment(cell, comment); } protected void AddFormulaRange(ExcelWorksheet worksheet, int startRow, int startCol, int endRow, int endCol, string value, CellStyle cellStyle, string comment = null) { var cell = AddFormulaRange(worksheet, startRow, startCol, endRow, endCol, value); ChangeStyle(cell, cellStyle ?? NamedCellStyles["IntegerStyle"]); AddComment(cell, comment); } protected int AddDataTableCol(ExcelWorksheet worksheet, int trow, int tcol, DataTable dataTable, int dtCol, CellStyle cellStyle, string customheader = null, CellStyle headerCellStyle = null, string aggregateFunc = null, CellStyle formulaCellStyle = null) { return AddDataTableCol(worksheet, trow, tcol, dataTable, dataTable.Columns[dtCol].ToString(), cellStyle, customheader, headerCellStyle, aggregateFunc, formulaCellStyle); } protected int AddDataTableCol(ExcelWorksheet worksheet, int trow, int tcol, DataTable dataTable, string dtCol, CellStyle cellStyle, string customHeader = null, CellStyle headerCellStyle = null, string aggregateFunc = null, CellStyle formulaCellStyle = null) { if (trow < 1 || tcol < 1) return 0; var row = 0; var rowOffset = 0; DataColumnCollection columns = dataTable.Columns; if (columns.Contains(dtCol)) { bool aggregatedValues = false; if (customHeader != null) { AddLabelCell(worksheet, trow, tcol, customHeader, headerCellStyle); rowOffset++; } for (; row < dataTable.Rows.Count; row++) aggregatedValues = AddCellWithTypeCheck(worksheet, trow + rowOffset + row, tcol, dataTable.Rows[row][dtCol], cellStyle); if (aggregatedValues && row > 0 && aggregateFunc != null) AddFormulaCell(worksheet, trow + rowOffset + row++, tcol, "=" + aggregateFunc + "(" + ColumnLabel(tcol) + (trow + rowOffset) + ":" + ColumnLabel(tcol) + (trow + rowOffset + row - 2) + ")", formulaCellStyle); else if (!aggregatedValues && row > 0 && aggregateFunc != null) row++; } return row + rowOffset; } protected int AddDataTableColTransponalt(ExcelWorksheet worksheet, int trow, int tcol, DataTable dataTable, string dtCol, CellStyle cellStyle, string customHeader = null, CellStyle headerCellStyle = null, string aggregateFunc = null, CellStyle formulaCellStyle = null) { if (trow < 1 || tcol < 1) return 0; var rowColl = 0; var collOffset = 0; DataColumnCollection columns = dataTable.Columns; if (columns.Contains(dtCol)) { bool aggregatedValues = false; if (customHeader != null) { AddLabelCell(worksheet, trow, tcol, customHeader, headerCellStyle); collOffset++; } for (; rowColl < dataTable.Rows.Count; rowColl++) aggregatedValues = AddCellWithTypeCheck(worksheet, trow, tcol + collOffset + rowColl, dataTable.Rows[rowColl][dtCol], cellStyle); if (aggregatedValues && rowColl > 0 && aggregateFunc != null) AddFormulaCell(worksheet, trow, tcol + collOffset + rowColl++, "=" + aggregateFunc + "(" + ColumnLabel(tcol + collOffset) + trow + ":" + ColumnLabel(tcol + collOffset + rowColl - 2) + trow + ")", formulaCellStyle); else if (!aggregatedValues && rowColl > 0 && aggregateFunc != null) rowColl++; } return rowColl + collOffset; } protected int[] AddDataTableRow(ExcelWorksheet worksheet, int trow, int tcol, DataTable dataTable, string criteria, CellStyle cellStyle, string[] dtCols = null, string aggregateFunc = null, CellStyle formulaCellStyle = null) { int[] insertDim = { 0/*rows*/, 0 /*cols*/}; if (trow < 1 || tcol < 1) return insertDim; DataRow[] filteredRows = dataTable.Select(criteria); DataColumnCollection columns = dataTable.Columns; if (dtCols == null) dtCols = columns.Cast().Select(x => x.ColumnName).ToArray(); if (filteredRows.Length > 0) { bool aggregatedValues = false; insertDim[0] = filteredRows.Length; var col = 0; for (int row = 0; row < filteredRows.Length; row++) { col = 0; foreach (string dtCol in dtCols) { if (columns.Contains(dtCol)) { aggregatedValues = AddCellWithTypeCheck(worksheet, trow + row, tcol + col, filteredRows[row][dtCol], cellStyle); col++; } } if (aggregatedValues && aggregateFunc != null) { AddFormulaCell(worksheet, trow + row, tcol + dtCols.Length, "=" + aggregateFunc + "(" + ColumnLabel(tcol) + (trow + row) + ":" + ColumnLabel(tcol + dtCols.Length - 1) + (trow + row) + ")", formulaCellStyle); insertDim[1]++; } } insertDim[1] = col; } return insertDim; } protected int[] AddDataTable ( ExcelWorksheet worksheet, int trow, int tcol, DataTable dataTable, string criteria, CellStyle cellDefaultStyle, CellStyle headerDefaultStyle, CellStyle[] cellStyles = null, CellStyle[] headerStyles = null, string[] dtCols = null, string rowAggregateFunc = null, CellStyle rowFormulaCellStyle = null, int rowHeaderOffset = 0, string[] columnAggregateFuncs = null, string[] columnAggregateFuncHeaderCol = null, CellStyle[] columnFormulaCellStyles = null, CellStyle columnFormulaCellHeaderStyles = null //ColumnAggregates ) { int[] insertDim = { 0/*rows*/, 0 /*cols*/}; if (trow < 1 || tcol < 1) return insertDim; DataRow[] filteredRows = dataTable.Select(criteria); DataColumnCollection columns = dataTable.Columns; int headerCount = 0; if (dtCols == null) { dtCols = columns.Cast().Select(x => x.ColumnName).ToArray(); headerCount = 1; int tHeaderColNum = tcol; foreach (var col in dtCols) { AddLabelCell(worksheet, trow, tHeaderColNum, col.IndexOf("COLUMN", StringComparison.OrdinalIgnoreCase) >= 0 ? Resources.ExcelNyomtatvanyResource.ResourceManager.GetString(col.ToUpper()) : col, (headerStyles?.Length ?? 0) > (tHeaderColNum - tcol) ? headerStyles[tHeaderColNum - tcol] : headerDefaultStyle); tHeaderColNum++; } } if (filteredRows.Length > 0) { bool aggregatedValues = false; insertDim[0] = headerCount + filteredRows.Length + (columnAggregateFuncs?.Length ?? 0); var col = 0; int row = 0; for (; row < filteredRows.Length; row++) { col = 0; int currentRowNum = trow + headerCount + row; foreach (string dtCol in dtCols) { if (columns.Contains(dtCol)) { aggregatedValues = AddCellWithTypeCheck(worksheet, currentRowNum, tcol + col, filteredRows[row][dtCol], (cellStyles?.Length ?? 0) > col ? cellStyles[col] : cellDefaultStyle); col++; } } if (aggregatedValues && rowAggregateFunc != null) { AddFormulaCell(worksheet, currentRowNum, tcol + dtCols.Length, "=" + rowAggregateFunc + "(" + ColumnLabel(tcol) + currentRowNum + ":" + ColumnLabel(tcol + dtCols.Length - 1) + currentRowNum + ")", rowFormulaCellStyle); insertDim[1]++; } } insertDim[1] = col; if (columnAggregateFuncs != null) { for (var funcrow = 0; funcrow < columnAggregateFuncs.Length; funcrow++) { var formularow = trow + headerCount + row + funcrow; var vaggregateFuncHeader = columnAggregateFuncHeaderCol != null && columnAggregateFuncHeaderCol.Length > funcrow ? columnAggregateFuncHeaderCol[funcrow] : null; if (vaggregateFuncHeader != null) AddLabelCell(worksheet, formularow, tcol, vaggregateFuncHeader, columnFormulaCellHeaderStyles ?? ((cellStyles?.Length ?? 0) > col ? cellStyles[col] : cellDefaultStyle)); var vaggregateFunc = columnAggregateFuncs[funcrow]; CellStyle colFormulaCellStyle = columnFormulaCellStyles != null && columnFormulaCellStyles.Length > funcrow ? columnFormulaCellStyles[funcrow] : cellDefaultStyle; for (col = rowHeaderOffset; col < dtCols.Length; col++) { int formulacol = tcol + col; AddAggregateFormulaCell(worksheet, formularow, formulacol, vaggregateFunc, trow + headerCount, formulacol, trow + headerCount + row - 1, formulacol, true, colFormulaCellStyle); } } } } return insertDim; } protected bool AddDataTablePivotTableCell(ExcelWorksheet worksheet, int trow, int tcol, DataTable dataTable, string criteria, CellStyle cellStyle, string[] dtCols = null, string[] dtCommentCols = null) { bool aggregatedValue = false; if (trow < 1 || tcol < 1) return aggregatedValue; DataRow[] filteredRows = dataTable.Select(criteria); if (filteredRows.Length > 0) { DataColumnCollection columns = dataTable.Columns; if (dtCols == null) dtCols = columns.Cast().Select(x => x.ColumnName).ToArray(); for (int row = 0; row < filteredRows.Length; row++) { var col = 0; foreach (string dtCol in dtCols) { if (columns.Contains(dtCol)) { string comment = null; if (dtCommentCols != null) { foreach (string dtCommentCol in dtCommentCols) { object commentValue = filteredRows[row][dtCommentCol]; if (columns.Contains(dtCommentCol) && !(commentValue is DBNull)) comment = (string)commentValue; } } aggregatedValue = AddCellWithTypeCheck(worksheet, trow + row, tcol + col, filteredRows[row][dtCol], cellStyle, comment); col++; } } } } else { aggregatedValue = AddCellWithTypeCheck(worksheet, trow, tcol, "", cellStyle); } return aggregatedValue; } protected int[] AddDataTablePivotTable ( ExcelWorksheet worksheet, int trow, int tcol, //Worksheet DataTable dataTableHeader, string headerFilterDtCols, string headershowDtCol, //TableHeader DataTable dataTableRowHeader, string rowHeadersFilteDtCols, string[] rowHeaderDtCols, //RowHeader DataTable dataTable, //DataTable CellStyle cellStyle, CellStyle headerCellStyle = null, CellStyle rowHeaderCellStyle = null, //Styles string[] dtCols = null, string[] dtCommentCols = null, //DataTableFields string[] rowAggregateFuncs = null, string[] rowAggregateFuncHeaderCol = null, CellStyle[] rowFormulaCellStyles = null, //RowAggregates string[] columnAggregateFuncs = null, string[] columnAggregateFuncHeaderCol = null, CellStyle[] columnFormulaCellStyles = null //ColumnAggregates ) { return AddDataTablePivotTable ( worksheet, trow, tcol, dataTableHeader, headerFilterDtCols != null ? new[] { headerFilterDtCols } : null, headershowDtCol, dataTableRowHeader, rowHeadersFilteDtCols != null ? new[] { rowHeadersFilteDtCols } : null, rowHeaderDtCols, dataTable, cellStyle, headerCellStyle, rowHeaderCellStyle, dtCols, dtCommentCols, rowAggregateFuncs, rowAggregateFuncHeaderCol, rowFormulaCellStyles, columnAggregateFuncs, columnAggregateFuncHeaderCol, columnFormulaCellStyles ); } protected int[] AddDataTablePivotTable ( ExcelWorksheet worksheet, int trow, int tcol, //Worksheet DataTable dataTableHeader, string[] headerFilterDtCols, string headershowDtCol, //TableHeader DataTable dataTableRowHeader, string[] rowHeadersFilteDtCols, string[] rowHeaderDtCols, //RowHeader DataTable dataTable, //DataTable CellStyle cellStyle, CellStyle headerCellStyle = null, CellStyle rowHeaderCellStyle = null, //Styles string[] dtCols = null, string[] dtCommentCols = null, //DataTableFields string[] rowAggregateFuncs = null, string[] rowAggregateFuncHeaderCol = null, CellStyle[] rowFormulaCellStyles = null, //RowAggregates string[] columnAggregateFuncs = null, string[] columnAggregateFuncHeaderCol = null, CellStyle[] columnFormulaCellStyles = null //ColumnAggregates ) { int[] insertDim = { 0/*rows*/, 0 /*cols*/}; if (trow < 1 || tcol < 1) return insertDim; var rowHeaderOffset = rowHeaderDtCols?.Length ?? 0; if (headershowDtCol != null) AddDataTableColTransponalt(worksheet, trow, tcol + rowHeaderOffset, dataTableHeader, headershowDtCol, headerCellStyle ?? cellStyle); if (rowHeaderOffset > 0) AddDataTableRow(worksheet, trow + 1, tcol, dataTableRowHeader, "", rowHeaderCellStyle ?? cellStyle, rowHeaderDtCols); const int headerCount = 1; var row = 0; List colFilters = new List(); /*Fejléc filterek összeállítása*/ foreach (DataRow dtRow in dataTableHeader.Rows) { var colFilter = ""; foreach (var headerFilterDtCol in headerFilterDtCols) { object dtvalue = dtRow[headerFilterDtCol]; switch (dtvalue) { case int _: case double _: case string _ when int.TryParse((string)dtvalue, out int intDtvalue): case string _ when double.TryParse((string)dtvalue, out double doubleDtValue): break; default: dtvalue = "'" + dtvalue + "'"; break; } colFilter += (colFilter.Length > 0 ? " AND " : "") + headerFilterDtCol + "=" + dtvalue; } colFilters.Add(colFilter); } /*Sorok feldolgozása*/ for (; row < dataTableRowHeader.Rows.Count; row++) { var rowFilter = ""; foreach (var rowHeadersFilteDtCol in rowHeadersFilteDtCols) { object dtvalue = dataTableRowHeader.Rows[row][rowHeadersFilteDtCol]; switch (dtvalue) { case int _: case double _: case string _ when int.TryParse((string)dtvalue, out int intDtvalue): case string _ when double.TryParse((string)dtvalue, out double doubleDtValue): break; default: dtvalue = "'" + dtvalue + "'"; break; } rowFilter += (rowFilter.Length > 0 ? " AND " : "") + rowHeadersFilteDtCol + "=" + dtvalue; } /*Sor adataival szűrt adattábla ellenőrzés, szűrés*/ DataRow[] filteredRows = dataTable.Select(rowFilter); if (filteredRows.Length > 0) { DataTable rowFilteredTable = filteredRows.AsEnumerable().CopyToDataTable(); /*Oszlopok összeállítása*/ var col = 0; foreach (string colFilter in colFilters) { AddDataTablePivotTableCell(worksheet, trow + headerCount + row, tcol + rowHeaderOffset + col, rowFilteredTable, colFilter, cellStyle, dtCols, dtCommentCols); col++; } } else { var col = 0; foreach (string colFilter in colFilters) { AddCellWithTypeCheck(worksheet, trow + headerCount + row, tcol + rowHeaderOffset + col, "", cellStyle); col++; } } if (rowAggregateFuncs != null) { var formularow = trow + headerCount + row; var formulacol = tcol + rowHeaderOffset + colFilters.Count; for (int funccol = 0; funccol < rowAggregateFuncs.Length; funccol++) { if (rowAggregateFuncs[funccol] == null) { continue; } string aggregateFuncHeader = (rowAggregateFuncHeaderCol != null && rowAggregateFuncHeaderCol.Length > funccol ? rowAggregateFuncHeaderCol[funccol] : ""); CellStyle formulaCellStyle = (rowFormulaCellStyles != null && rowFormulaCellStyles.Length > funccol ? rowFormulaCellStyles[funccol] : cellStyle); AddLabelCell(worksheet, trow, formulacol + funccol, aggregateFuncHeader, headerCellStyle ?? cellStyle); AddAggregateFormulaCell(worksheet, formularow, formulacol + funccol, rowAggregateFuncs[funccol], formularow, tcol + rowHeaderOffset, formularow, formulacol - 1, true, formulaCellStyle); } } } if (columnAggregateFuncs != null) { for (var funcrow = 0; funcrow < columnAggregateFuncs.Length; funcrow++) { var formularow = trow + headerCount + row + funcrow; var vaggregateFuncHeader = columnAggregateFuncHeaderCol != null && columnAggregateFuncHeaderCol.Length > funcrow ? columnAggregateFuncHeaderCol[funcrow] : ""; CellStyle formulaCellStyle = columnFormulaCellStyles != null && columnFormulaCellStyles.Length > funcrow ? columnFormulaCellStyles[funcrow] : cellStyle; AddLabelCell(worksheet, formularow, tcol, vaggregateFuncHeader, rowHeaderCellStyle ?? cellStyle); for (var col = 0; col < dataTableHeader.Rows.Count; col++) { int formulacol = tcol + rowHeaderOffset + col; AddAggregateFormulaCell(worksheet, formularow, formulacol, columnAggregateFuncs[funcrow], trow + headerCount, formulacol, trow + headerCount + row - 1, formulacol, true, formulaCellStyle); } } } insertDim[0] = row + headerCount + (columnAggregateFuncs?.Length ?? 0); insertDim[1] = rowHeaderOffset + dataTableHeader.Rows.Count + (rowAggregateFuncs?.Length ?? 0); return insertDim; } public void GenerateNewExcelPackage(string templateFilename = null) { FileInfo exFile = null; if (templateFilename != null) { exFile = new FileInfo(templateFilename); } ExcelPackage = (exFile == null) ? new ExcelPackage() : new ExcelPackage(exFile); } public void Dispose() { ExcelPackage?.Dispose(); DataSet?.Dispose(); } } }