/// <summary>C:\Users\User\source\repos\ExcelWorkVariances\ExcelDataHandler\packages.config
        /// Method creates Pivot table
        /// </summary>
        /// <param name="worksheet"></param>
        public static void CreateMyPivotTable(Excel.Application app, Excel.Workbook workbook, Excel.Worksheet worksheet)
        {
            Excel.Worksheet secondWorksheet = workbook.Sheets.Add();
            try
            {
                secondWorksheet.Name = "pivot_table";
                app.ActiveWindow.DisplayGridlines = false;
                Excel.Range       oRange      = worksheet.UsedRange;
                Excel.PivotCache  oPivotCache = workbook.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, oRange);                                      // Set the Source data range from First sheet
                Excel.PivotCaches pch         = workbook.PivotCaches();
                pch.Add(Excel.XlPivotTableSourceType.xlDatabase, oRange).CreatePivotTable(secondWorksheet.Cells[1, 1], "Confidence", Type.Missing, Type.Missing); // Create Pivot table

                Excel.PivotTable pvt = secondWorksheet.PivotTables("Confidence");
                pvt.ShowDrillIndicators = true;
                pvt.InGridDropZones     = false;

                Excel.PivotField fld = ((Excel.PivotField)pvt.PivotFields("ID"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                fld.set_Subtotals(1, false);

                fld             = ((Excel.PivotField)pvt.PivotFields("CATEGORY"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                fld.set_Subtotals(1, false);

                fld             = ((Excel.PivotField)pvt.PivotFields("PLACE"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                fld.set_Subtotals(1, false);

                fld             = ((Excel.PivotField)pvt.PivotFields("NAME"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                fld.set_Subtotals(1, false);

                fld             = ((Excel.PivotField)pvt.PivotFields("PRICE"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                fld.set_Subtotals(1, false);

                fld             = ((Excel.PivotField)pvt.PivotFields("UNITS"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlDataField;

                secondWorksheet.UsedRange.Columns.AutoFit();
                pvt.ColumnGrand   = true;
                pvt.RowGrand      = true;
                app.DisplayAlerts = false;
                secondWorksheet.Activate();
                secondWorksheet.get_Range("B1", "B1").Select();
                worksheet.Activate();
            }
            catch (Exception)
            {
            }
        }
예제 #2
0
        public static void CreatePivotTable(Excel.Application app, Excel.Workbook workbook, Excel.Worksheet worksheet)
        {
            Excel.Worksheet secondWorksheet = (Worksheet)workbook.Sheets.Add();
            try
            {
                Excel.Range last  = worksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
                Excel.Range range = worksheet.get_Range("G1", last);

                int lastUsedRow    = last.Row;
                int lastUsedColumn = last.Column;

                Excel.Range oResizeRange = worksheet.Range[worksheet.Cells[1, 7],
                                                           worksheet.Cells[lastUsedRow, lastUsedColumn]];

                secondWorksheet.Name = "pivot_table";
                app.ActiveWindow.DisplayGridlines = false;
                //Excel.Range oRange = worksheet.UsedRange;
                Excel.PivotCache  oPivotCache = workbook.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, oResizeRange);                                                  // Set the Source data range from First sheet
                Excel.PivotCaches pch         = workbook.PivotCaches();
                pch.Add(Excel.XlPivotTableSourceType.xlDatabase, oResizeRange).CreatePivotTable(secondWorksheet.Cells[1, 1], "Confidence and Latency", Type.Missing, Type.Missing); // Create Pivot table

                Excel.PivotTable pvt = (Excel.PivotTable)secondWorksheet.PivotTables("Labels");
                pvt.ShowDrillIndicators = true;
                pvt.InGridDropZones     = false;

                Excel.PivotField fld = ((Excel.PivotField)pvt.PivotFields("Confidence"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                fld.set_Subtotals(1, false);

                fld             = ((Excel.PivotField)pvt.PivotFields("Latency"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                fld.set_Subtotals(1, false);

                secondWorksheet.UsedRange.Columns.AutoFit();
                pvt.ColumnGrand   = true;
                pvt.RowGrand      = true;
                app.DisplayAlerts = false;
                secondWorksheet.Activate();
                secondWorksheet.get_Range("B1", "B1").Select();
            }
            catch (Exception)
            {
                // ignored
            }

            //worksheet.Select();
            worksheet.Activate();
        }
예제 #3
0
        public void CreatePivot(string sheetName, int colCount, int rowCount, string pivotTableLocation, string pivotTableName, string rowField, string rowHeader, string columnField, string columnHeader)
        {
            #region Initialization
            Excel.Workbook    activeWorkBook   = null;
            Excel.Worksheet   pivotWorkSheet   = null;
            Excel.PivotCaches pivotCaches      = null;
            Excel.PivotCache  pivotCache       = null;
            Excel.PivotTable  pivotTable       = null;
            Excel.PivotFields pivotFields      = null;
            Excel.PivotField  rowPivotField    = null;
            Excel.PivotField  columnPivotField = null;
            Excel.PivotField  countPivotField  = null;
            Excel.PivotItems  pivotItems       = null;
            Excel.Range       pivotRange       = null;

            Excel.PivotField hiddenPivotField = null;

            #endregion

            try
            {
                activeWorkBook = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.ActiveWorkbook;
                pivotWorkSheet = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.ActiveSheet;

                // Create the Pivot Table
                pivotCaches = activeWorkBook.PivotCaches();
                activeWorkBook.ShowPivotTableFieldList = false;
                string rangeName = "'" + sheetName + "'!$A$4:$" + ExcelColumnLetter(colCount - 1) + "$" + (rowCount + 4).ToString();
                pivotCache               = pivotCaches.Create(Excel.XlPivotTableSourceType.xlDatabase, rangeName);
                pivotTable               = pivotCache.CreatePivotTable(pivotTableLocation, pivotTableName);
                pivotTable.NullString    = "0";
                pivotTable.HasAutoFormat = false;

                // Set the Pivot Fields
                pivotFields = (Excel.PivotFields)pivotTable.PivotFields();

                // Row Pivot Field
                rowPivotField                     = (Excel.PivotField)pivotFields.Item(rowField);
                rowPivotField.Orientation         = Excel.XlPivotFieldOrientation.xlRowField;
                rowPivotField.Position            = 1;
                pivotTable.CompactLayoutRowHeader = rowHeader;

                // Column Pivot Field
                columnPivotField = (Excel.PivotField)pivotFields.Item(columnField);
                // Causes error and not needed
                // columnPivotField.Orientation = Excel.XlPivotFieldOrientation.xlColumnField;

                // Count Field
                countPivotField = pivotTable.AddDataField(columnPivotField, columnHeader, Excel.XlConsolidationFunction.xlCount);

                pivotTable.PivotFields(rowField).AutoSort(Excel.XlSortOrder.xlDescending, columnHeader);

                // Show only Top 10 results for the pivot table
                int top10 = 10;
                // pivotWorkSheet.PivotTables(pivotTableName).PivotFields(rowField).PivotFilters.Add2(Type: Excel.XlPivotFilterType.xlTopCount,
                //            DataField: pivotWorkSheet.PivotTables(pivotTableName).PivotFields(columnHeader), Value1: top10);

                if (Globals.ExcelVersion == "15.0" || Globals.ExcelVersion == "16.0")
                {
                    pivotWorkSheet.PivotTables(pivotTableName).PivotFields(rowField).PivotFilters.Add2(Type: Excel.XlPivotFilterType.xlTopCount,
                                                                                                       DataField: pivotWorkSheet.PivotTables(pivotTableName).PivotFields(columnHeader), Value1: top10);
                }
                else
                {
                    pivotWorkSheet.PivotTables(pivotTableName).PivotFields(rowField).PivotFilters.Add(Type: Excel.XlPivotFilterType.xlTopCount,
                                                                                                      DataField: pivotWorkSheet.PivotTables(pivotTableName).PivotFields(columnHeader), Value1: top10);
                }

                string cellValue = "";
                pivotRange = pivotTable.RowRange;
                int itemCount = pivotRange.Count - 2;  // Minus 2 because of title and total rows

                if (itemCount > top10)
                {
                    pivotItems = pivotWorkSheet.PivotTables(pivotTableName).PivotFields(rowField).PivotItems;
                    for (int i = itemCount - 1; i >= top10; i--)
                    {
                        cellValue = (string)(pivotWorkSheet.Cells[pivotRange.Row + i + 1, pivotRange.Column] as Excel.Range).Value.ToString();
                        pivotItems.Item(cellValue).Visible = false;
                    }
                }

                if (pivotTableName == "PivotTableAtRiskUsers")
                {
                    Globals.MostAtRiskUser = (string)(pivotWorkSheet.Cells[pivotRange.Row + 1, pivotRange.Column] as Excel.Range).Value.ToString();
                }
                else if (pivotTableName == "PivotTableAtRiskGroups")
                {
                    Globals.MostAtRiskGroup = (string)(pivotWorkSheet.Cells[pivotRange.Row + 1, pivotRange.Column] as Excel.Range).Value.ToString();
                }
                else if (pivotTableName == "PivotTableAtRiskEndpoints")
                {
                    Globals.MostAtRiskEndpoint = (string)(pivotWorkSheet.Cells[pivotRange.Row + 1, pivotRange.Column] as Excel.Range).Value.ToString();
                }

                string reportTable = "";
                string reportLabel = "\"";
                string reportValue = "";

                reportTable = "<table id=\"newspaper-a\" class=\"sortable\">";

                string head1 = (string)(pivotWorkSheet.Cells[pivotRange.Row, pivotRange.Column] as Excel.Range).Value.ToString();
                string head2 = (string)(pivotWorkSheet.Cells[pivotRange.Row, pivotRange.Column + 1] as Excel.Range).Value.ToString();
                reportTable = reportTable +
                              "<thead><tr><th scope=\"col\">" + head1 + "</th><th style=\"text-align:right;\" scope=\"col\" nowrap>" + head2 + "</th></tr></thead><tbody>";
                string col1         = "";
                string col2         = "";
                string labelShorted = "";
                int    tableItems   = itemCount > 10 ? 10 : itemCount;
                for (int i = 1; i <= tableItems; i++)
                {
                    col1        = (string)(pivotWorkSheet.Cells[pivotRange.Row + i, pivotRange.Column] as Excel.Range).Value.ToString();
                    col2        = (string)(pivotWorkSheet.Cells[pivotRange.Row + i, pivotRange.Column + 1] as Excel.Range).Value.ToString();
                    reportTable = reportTable + "<tr><td>" + col1 + "</td><td  style=\"text-align:right;\">" + col2 + "</td></tr>";

                    if (tableItems > 5 && col1.Length > 10)
                    {
                        labelShorted = col1.Substring(0, 10) + "..";
                    }
                    else if (col1.Length > 20)
                    {
                        labelShorted = col1.Substring(0, 20) + "..";
                    }
                    else
                    {
                        labelShorted = col1;
                    }

                    reportLabel = reportLabel + labelShorted + "\",\"";
                    reportValue = reportValue + col2 + ",";
                }
                string foot1 = (string)(pivotWorkSheet.Cells[pivotRange.Row + tableItems + 1, pivotRange.Column] as Excel.Range).Value.ToString();
                string foot2 = (string)(pivotWorkSheet.Cells[pivotRange.Row + tableItems + 1, pivotRange.Column + 1] as Excel.Range).Value.ToString();
                reportTable = reportTable +
                              "</tbody><tfoot><tr><td>" + foot1 + "</td><td  style=\"text-align:right;\">" + foot2 + "</td></tr></tfoot></table>";
                reportValue = reportValue.TrimEnd(',');
                reportLabel = reportLabel.TrimEnd('\"');
                reportLabel = reportLabel.TrimEnd(',');

                if (pivotTableName == "PivotTableClassifier")
                {
                    Globals.DetectionEngine       = reportTable;
                    Globals.DetectionEnginesLabel = reportLabel;
                    Globals.DetectionEnginesValue = reportValue;
                }
                else if (pivotTableName == "PivotTableFileDisplayName")
                {
                    Globals.InfectedFiles      = reportTable;
                    Globals.InfectedFilesLabel = reportLabel;
                    Globals.InfectedFilesValue = reportValue;
                }
                else if (pivotTableName == "PivotTableAtRiskGroups")
                {
                    Globals.MostAtRiskGroups      = reportTable;
                    Globals.MostAtRiskGroupsLabel = reportLabel;
                    Globals.MostAtRiskGroupsValue = reportValue;
                }
                else if (pivotTableName == "PivotTableAtRiskUsers")
                {
                    Globals.MostAtRiskUsers      = reportTable;
                    Globals.MostAtRiskUsersLabel = reportLabel;
                    Globals.MostAtRiskUsersValue = reportValue;
                }
                else if (pivotTableName == "PivotTableAtRiskEndpoints")
                {
                    Globals.MostAtRiskEndpoints      = reportTable;
                    Globals.MostAtRiskEndpointsLabel = reportLabel;
                    Globals.MostAtRiskEndpointsValue = reportValue;
                }
                else if (pivotTableName == "PivotTableIsActive")
                {
                    Globals.NetworkStatus      = reportTable;
                    Globals.NetworkStatusLabel = reportLabel;
                    Globals.NetworkStatusValue = reportValue;
                }
                else if (pivotTableName == "PivotTableOs")
                {
                    Globals.EndpointOS      = reportTable;
                    Globals.EndpointOSLabel = reportLabel;
                    Globals.EndpointOSValue = reportValue;
                }
                else if (pivotTableName == "PivotTableAgent")
                {
                    Globals.EndpointVersion      = reportTable;
                    Globals.EndpointVersionLabel = reportLabel;
                    Globals.EndpointVersionValue = reportValue;
                }
                else if (pivotTableName == "PivotTableApplicationName")
                {
                    Globals.TopApplications      = reportTable;
                    Globals.TopApplicationsLabel = reportLabel;
                    Globals.TopApplicationsValue = reportValue;
                }


                Excel.Range colToFormat = pivotWorkSheet.get_Range("K:Q", System.Type.Missing);
                colToFormat.EntireColumn.AutoFit();

                Excel.Range colToEdit = pivotWorkSheet.get_Range("K:K", System.Type.Missing);
                // Was 28, changed 11/9/2017
                if (pivotTableName == "PivotTableApplicationName")
                {
                    colToEdit.EntireColumn.ColumnWidth = 70;
                }
                else if (colToEdit.EntireColumn.ColumnWidth > 35)
                {
                    colToEdit.EntireColumn.ColumnWidth = 35;
                }

                // Customizing the pivot table style
                pivotWorkSheet.PivotTables(pivotTableName).TableStyle2 = "PivotStyleMedium9";

                // Remembers the bottom of the pivot table so that the next one will not overlap
                Globals.PivotBottom = pivotTable.TableRange2.Cells.SpecialCells(Excel.XlCellType.xlCellTypeVisible).Row + pivotTable.TableRange2.Cells.SpecialCells(Excel.XlCellType.xlCellTypeVisible).Rows.Count;
                Excel.Range rng = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range("A" + Globals.PivotBottom.ToString(), "A" + Globals.PivotBottom.ToString());
                // Globals.ChartBottom = (int)rng.Top + (int)rng.Height;
            }
            catch (Exception ex)
            {
                (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.Cells[3, 3] = ex.Message;

                /*
                 * Excel.PivotTable pt = pivotWorkSheet.PivotTables(pivotTableName);
                 * Excel.Range pr = pt.TableRange2;
                 * pr.Clear();
                 */
            }
            finally
            {
                #region Finally
                if (countPivotField != null)
                {
                    Marshal.ReleaseComObject(countPivotField);
                }
                if (columnPivotField != null)
                {
                    Marshal.ReleaseComObject(columnPivotField);
                }
                if (rowPivotField != null)
                {
                    Marshal.ReleaseComObject(rowPivotField);
                }
                if (pivotFields != null)
                {
                    Marshal.ReleaseComObject(pivotFields);
                }
                if (pivotTable != null)
                {
                    Marshal.ReleaseComObject(pivotTable);
                }
                if (pivotCache != null)
                {
                    Marshal.ReleaseComObject(pivotCache);
                }
                if (pivotCaches != null)
                {
                    Marshal.ReleaseComObject(pivotCaches);
                }
                if (activeWorkBook != null)
                {
                    Marshal.ReleaseComObject(activeWorkBook);
                }
                if (pivotWorkSheet != null)
                {
                    Marshal.ReleaseComObject(pivotWorkSheet);
                }
                #endregion
            }
        }
예제 #4
0
        //this method will create pivot table in excel file
        public string OfficeDll()
        {
            string filepath = System.Web.HttpContext.Current.Server.MapPath("~/Content/ProductReport.xlsx");
            int    rows     = 0;

            Excel.Application excelApp       = new Excel.Application();
            Excel.Workbook    excelWorkBook  = excelApp.Workbooks.Open(filepath);
            Excel.Worksheet   excelworksheet = excelWorkBook.ActiveSheet;
            Excel.Worksheet   sheet2         = excelWorkBook.Sheets.Add();
            try
            {
                sheet2.Name = "Pivot Table";
                excelApp.ActiveWindow.DisplayGridlines = false;
                Excel.Range       oRange      = excelworksheet.UsedRange;
                Excel.PivotCache  oPivotCache = excelWorkBook.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, oRange);                      // Set the Source data range from First sheet
                Excel.PivotCaches pch         = excelWorkBook.PivotCaches();
                pch.Add(Excel.XlPivotTableSourceType.xlDatabase, oRange).CreatePivotTable(sheet2.Cells[3, 3], "PivTbl_2", Type.Missing, Type.Missing); // Create Pivot table
                Excel.PivotTable pvt = sheet2.PivotTables("PivTbl_2");
                pvt.ShowDrillIndicators = true;
                pvt.InGridDropZones     = false;
                Excel.PivotField fld = ((Excel.PivotField)pvt.PivotFields("CATEGORY"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                fld.set_Subtotals(1, false);

                fld             = ((Excel.PivotField)pvt.PivotFields("PLACE"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                fld.set_Subtotals(1, false);

                fld             = ((Excel.PivotField)pvt.PivotFields("NAME"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                fld.set_Subtotals(1, false);

                fld             = ((Excel.PivotField)pvt.PivotFields("PRICE"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                fld.set_Subtotals(1, false);

                fld             = ((Excel.PivotField)pvt.PivotFields("NoOfUnits"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlDataField;

                sheet2.UsedRange.Columns.AutoFit();
                pvt.ColumnGrand        = true;
                pvt.RowGrand           = true;
                excelApp.DisplayAlerts = false;
                excelworksheet.Delete();
                sheet2.Activate();
                sheet2.get_Range("B1", "B1").Select();
                excelWorkBook.SaveAs(filepath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                excelApp.DisplayAlerts = false;
                excelWorkBook.Close(0);
                excelApp.Quit();
                Marshal.ReleaseComObject(excelWorkBook);
                Marshal.ReleaseComObject(excelApp);
            }
            catch (Exception ex)
            {
                excelWorkBook.Close(0);
                excelApp.Quit();
                Marshal.ReleaseComObject(excelWorkBook);
                Marshal.ReleaseComObject(excelApp);

                return(ex.Message);
            }
            return(filepath);
        }
예제 #5
0
        public void generarReporte(DataGridView tabla, string nombreHojaReporte, string tituloReporte, string celdaInicioTitulo, string celdaFinTitulo, int indexInicioTitulo, int indexFinTitulo)
        {
            ////Para futura referencia, esta es una forma probable de obtener un rango de celdas basado en indices
            ////Excel.Range range = hoja.Ranges(hoja.Cells[1, 1], hoja.Cells[1, 2]);
            string columnaOrdenamiento = "Filtro";

            try
            {
                Cursor.Current   = Cursors.WaitCursor;
                exportar.Enabled = false;
                Microsoft.Office.Interop.Excel.Application excel     = new Microsoft.Office.Interop.Excel.Application();
                Microsoft.Office.Interop.Excel.Workbook    wb        = excel.Application.Workbooks.Add();
                Microsoft.Office.Interop.Excel.Worksheet   hojaDatos = wb.ActiveSheet;

                int IndiceColumna = 0;
                foreach (DataGridViewColumn col in tabla.Columns) // Columnas
                {
                    IndiceColumna++;
                    hojaDatos.Cells[1, IndiceColumna] = col.Name;
                }

                //agregar campo de ordenamiento
                hojaDatos.Cells[1, IndiceColumna + 1] = columnaOrdenamiento;
                int IndiceFila = 0;
                foreach (DataGridViewRow row in tabla.Rows) // Filas
                {
                    IndiceFila++;
                    IndiceColumna = 0;
                    foreach (DataGridViewColumn col in tabla.Columns)
                    {
                        IndiceColumna++;
                        hojaDatos.Cells[IndiceFila + 1, IndiceColumna] = "'" + row.Cells[col.Name].Value;
                    }
                    hojaDatos.Cells[IndiceFila + 1, IndiceColumna + 1] = columnaOrdenamiento;
                }

                Excel.Worksheet hojaReporte = excel.Sheets.Add();
                hojaReporte.Name = nombreHojaReporte;
                hojaReporte.Activate();

                Excel.Range oRange = hojaDatos.UsedRange;

                Excel.PivotCache  oPivotCache = wb.PivotCaches().Create(Excel.XlPivotTableSourceType.xlDatabase, oRange, Type.Missing);
                Excel.Range       oRange2     = hojaReporte.Cells[5, 2];
                Excel.PivotCaches pch         = wb.PivotCaches();
                pch.Add(Microsoft.Office.Interop.Excel.XlPivotTableSourceType.xlDatabase, oRange).CreatePivotTable(oRange2, "reportePersonas", Type.Missing, Type.Missing);
                Excel.PivotTable pvt = hojaReporte.PivotTables("reportePersonas") as Excel.PivotTable;

                //configuracion de la tabla dinamica
                pvt.RowGrand    = false;                          //Ocultar los totales y subtotales de la tabla dinamica
                pvt.ColumnGrand = false;                          //Ocultar los totales y subtotales de la tabla dinamica

                pvt.EnableFieldList          = false;             //desactivar la opcion para apagar o encender campos en la tabla dinamica
                pvt.ShowDrillIndicators      = false;             //quitar los simbolos de + en cada celda
                pvt.EnableDrilldown          = false;             //no permitir minimizar las filas
                pvt.InGridDropZones          = false;             //no permitir drag&drop de las columnas
                pvt.ShowTableStyleRowHeaders = false;             //no mostrar columna de por medio en negrita/otro color, segun el estilo de tabla
                pvt.TableStyle2 = "PivotStyleMedium9";            //settear estilo de tabla

                foreach (DataGridViewColumn col in tabla.Columns) // Columnas
                {
                    Excel.PivotField field = (Excel.PivotField)pvt.PivotFields(col.Name);
                    field.Orientation  = Excel.XlPivotFieldOrientation.xlRowField;
                    field.Subtotals[1] = false;
                }

                //agregar el PivotField para el campo de ordenamiento
                Excel.PivotField f = (Excel.PivotField)pvt.PivotFields(columnaOrdenamiento);
                f.Orientation = Excel.XlPivotFieldOrientation.xlDataField;
                f.Name        = "No remover, ocultar solamente";

                //hacer que las columnas tengan el tamaño adecuado
                hojaReporte.UsedRange.Columns.AutoFit();

                //int startIndex = indexColumnaOrdenamiento.IndexOfAny("0123456789".ToCharArray());
                //string indicatedColumnLetter = indexColumnaOrdenamiento.Substring(0, startIndex);

                string column = obtenerNombreColExcel(tabla.Columns.Count + 2); // se agregan mas dos por la posicion inicial de la tabla y la columna de ordenamiento extra

                hojaReporte.Range[column + "1"].EntireColumn.Hidden = true;     //ocultando la columna de sort

                //agregar el dato de encabezado
                hojaReporte.Cells[2, 3] = tituloReporte;
                Excel.Range titulo = hojaReporte.Range[celdaInicioTitulo, celdaFinTitulo];
                titulo.Merge();
                titulo.Font.Bold           = true;
                titulo.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                titulo.Borders[Excel.XlBordersIndex.xlEdgeBottom].Color = Color.Black;
                hojaReporte.Cells[3, indexInicioTitulo]     = "Fecha:";
                hojaReporte.Cells[3, indexInicioTitulo + 1] = DateTime.Today;
                hojaReporte.Cells[3, indexFinTitulo - 1]    = "Hora:";
                hojaReporte.Cells[3, indexFinTitulo]        = DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString();

                //eliminar la hoja de datos
                excel.DisplayAlerts = false; //bypass del bug que evita que se elimine la hoja
                hojaDatos.Activate();
                hojaDatos.Delete();
                hojaReporte.Activate();
                excel.DisplayAlerts = true; //retornar la propiedad al valor original
                MessageBox.Show("Infome generado exitosamente.", "Operación completa", MessageBoxButtons.OK, MessageBoxIcon.Information);
                exportar.Enabled = true;
                excel.Visible    = true;
                Cursor.Current   = Cursors.Default;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
                Cursor.Current   = Cursors.Default;
                exportar.Enabled = true;
                MessageBox.Show("Ha ocurrido un error en la creación del documento, póngase en contacto con los desarrolladores del sistema.", "Error - AlbergueHN", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public void Create()
        {
            Excel.Worksheet PivotSheet = this.PivotSheet;
            string          Location   = this.PivotTableLocation;
            string          TableName  = this.PivotTableName;
            char            Status     = this.Status;

            ListingSheet.Select();
            string LastRow  = "";
            string LastCol  = "";
            string LastCell = "";
            long   lRow     = 0;
            long   lCol     = 0;

            ////////////
            //FIND THE LAST NON-BLANK CELL IN COLUMN A
            lRow     = ListingSheet.Cells[ListingSheet.Rows.Count, 1].End(Excel.XlDirection.xlUp).Row;
            LastRow  = "R" + lRow;
            lCol     = ListingSheet.Cells[1, ListingSheet.Columns.Count].End(Excel.XlDirection.xlToLeft).Column;
            LastCol  = "C" + lCol;
            LastCell = ListingSheet.Cells[lRow, lCol].Address;

            Excel.Range PivotData = ListingSheet.Range["A1", LastCell];
            PivotData.Select();
            Excel.PivotCaches pch = ListingBook.PivotCaches();
            Excel.PivotCache  pc  = pch.Create(Excel.XlPivotTableSourceType.xlDatabase, PivotData);
            Excel.PivotTable  pvt = pc.CreatePivotTable(PivotSheet.Range[Location], TableName);
            PivotSheet.Select();

            Excel.PivotField pvf = pvt.PivotFields("Status");
            pvf.Orientation = Excel.XlPivotFieldOrientation.xlPageField;
            switch ((ListingStatus)Status)
            {
            case ListingStatus.Active:
            case ListingStatus.Sold:
                pvf.CurrentPage = Status.ToString();
                break;

            case ListingStatus.OffMarket:
                try { pvf.PivotItems(((char)ListingStatus.Active).ToString()).Visible = false; } catch (Exception e) { };
                try { pvf.PivotItems(((char)ListingStatus.Sold).ToString()).Visible = false; } catch (Exception e) { };
                try { pvf.PivotItems(((char)ListingStatus.Terminate).ToString()).Visible = true; } catch (Exception e) { };
                try { pvf.PivotItems(((char)ListingStatus.Cancel).ToString()).Visible = true; } catch (Exception e) { };
                try { pvf.PivotItems(((char)ListingStatus.Expire).ToString()).Visible = true; } catch (Exception e) { };
                pvf.EnableMultiplePageItems = true;
                break;
            }


            //Group 1 S/A
            pvt.PivotFields("S/A").Orientation = Excel.XlPivotFieldOrientation.xlRowField;
            pvt.PivotFields("S/A").Name        = "Neighborhood";
            //Group 2 Complex
            pvt.PivotFields("Complex/Subdivision Name").Orientation = Excel.XlPivotFieldOrientation.xlRowField;
            pvt.PivotFields("Complex/Subdivision Name").Name        = this.ReportType.ToString().IndexOf("Detached") < 0 ? "Complex" : "SubDivision";
            //Group 3 Address
            pvt.PivotFields("Address2").Orientation = Excel.XlPivotFieldOrientation.xlRowField;
            pvt.PivotFields("Address2").Name        = "Civic Address";
            //Group 4 UnitNo
            if (this.bShowUnitNo || this.ReportType.ToString().IndexOf("Detached") < 0)
            {
                pvt.PivotFields("Unit#").Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                pvt.PivotFields("Unit#").Name        = "Unit No";
            }

            pvt.AddDataField(pvt.PivotFields("MLS"), "Count", Excel.XlConsolidationFunction.xlCount);
            pvt.AddDataField(pvt.PivotFields("Price0"), "Price", Excel.XlConsolidationFunction.xlAverage);
            pvt.AddDataField(pvt.PivotFields("CDOM"), "Days On Mkt", Excel.XlConsolidationFunction.xlAverage);
            pvt.AddDataField(pvt.PivotFields("TotFlArea"), "Floor Area", Excel.XlConsolidationFunction.xlAverage);
            pvt.AddDataField(pvt.PivotFields("PrcSqft"), "$PSF", Excel.XlConsolidationFunction.xlAverage);
            //TEST Add Calculated Fields
            //Excel.PivotField ptField;
            //Excel.CalculatedFields cfField = pvt.CalculatedFields();
            //ptField = cfField.Add("New PSF", "='PrcSqft' * 'Age'", true);
            //pvt.AddDataField(ptField, " New PSF", Excel.XlConsolidationFunction.xlAverage);
            //
            pvt.AddDataField(pvt.PivotFields("Age"), "Building Age", Excel.XlConsolidationFunction.xlAverage);
            if (this.ReportType.ToString().IndexOf("Detached") < 0)
            {
                pvt.AddDataField(pvt.PivotFields("StratMtFee"), "Monthly Fee", Excel.XlConsolidationFunction.xlAverage);
            }
            else
            {
                pvt.AddDataField(pvt.PivotFields("Lot Sz (Sq.Ft.)"), "Land Size", Excel.XlConsolidationFunction.xlAverage);
                pvt.AddDataField(pvt.PivotFields("LandValue"), "Land Assess.", Excel.XlConsolidationFunction.xlAverage);
            }

            pvt.AddDataField(pvt.PivotFields("BCAValue"), "BC Assess.", Excel.XlConsolidationFunction.xlAverage);
            pvt.AddDataField(pvt.PivotFields("Change%"), "Chg% to BCA", Excel.XlConsolidationFunction.xlAverage);
            pvt.AddDataField(pvt.PivotFields("Lot$ PerSF"), "Lot$PSF", Excel.XlConsolidationFunction.xlAverage);
            pvt.AddDataField(pvt.PivotFields("Improve$ PerSF"), "Improve$PSF", Excel.XlConsolidationFunction.xlAverage);

            pvt.PivotFields("Price").NumberFormat        = "$#,##0";
            pvt.PivotFields("Days On Mkt").NumberFormat  = "0";
            pvt.PivotFields("Floor Area").NumberFormat   = "0";
            pvt.PivotFields("$PSF").NumberFormat         = "$#,##0";
            pvt.PivotFields("Building Age").NumberFormat = "0";
            if (this.ReportType.ToString().IndexOf("Detached") < 0)
            {
                pvt.PivotFields("Monthly Fee").NumberFormat = "$#,##0";
            }
            else
            {
                pvt.PivotFields("Land Size").NumberFormat    = "0";
                pvt.PivotFields("Land Assess.").NumberFormat = "$#,##0";
            }
            pvt.PivotFields("BC Assess.").NumberFormat  = "$#,##0";
            pvt.PivotFields("Chg% to BCA").NumberFormat = "0%";
            pvt.PivotFields("Lot$PSF").NumberFormat     = "$#,##0";
            pvt.PivotFields("Improve$PSF").NumberFormat = "$#,##0";

            pvt.RowAxisLayout(Excel.XlLayoutRowType.xlTabularRow);
        }
예제 #7
0
        public void CreateCityPivotTable(Excel.Worksheet PivotSheet, string Location, string TableName, ReportType TableType)
        {
            ListingSheet.Select();
            string LastRow       = "";
            string LastCol       = "";
            string LastCell      = "";
            long   lRow          = 0;
            long   lCol          = 0;
            string RankBaseField = "";

            ////////////
            //FIND THE LAST NON-BLANK CELL IN COLUMN A
            lRow     = ListingSheet.Cells[ListingSheet.Rows.Count, 1].End(Excel.XlDirection.xlUp).Row;
            LastRow  = "R" + lRow;
            lCol     = ListingSheet.Cells[1, ListingSheet.Columns.Count].End(Excel.XlDirection.xlToLeft).Column;
            LastCol  = "C" + lCol;
            LastCell = ListingSheet.Cells[lRow, lCol].Address;

            Excel.Range PivotData = ListingSheet.Range["A1", LastCell];
            PivotData.Select();
            Excel.PivotCaches pch = ListingBook.PivotCaches();
            Excel.PivotCache  pc  = pch.Create(Excel.XlPivotTableSourceType.xlDatabase, PivotData);
            Excel.PivotTable  pvt = pc.CreatePivotTable(PivotSheet.Range[Location], TableName);
            //pvt.MergeLabels = true; // The only thing I noticed this doing was centering the heading labels

            PivotSheet.Select();

            //Excel.PivotField pvf = pvt.PivotFields("Status");
            //pvf.Orientation = Excel.XlPivotFieldOrientation.xlPageField;
            //pvf.CurrentPage = Status;

            //Group 1 S/A
            switch (TableType)
            {
            case ReportType.MonthlyDetachedAllCities:
                pvt.PivotFields("City").Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                RankBaseField = "City";
                break;

            case ReportType.MonthlyDetachedAllCommunities:
                pvt.PivotFields("S/A").Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                pvt.PivotFields("S/A").Caption     = "Neighborhood";
                RankBaseField = "Neighborhood";
                break;

            default:
                break;
            }

            //pvt.PivotFields("S/A").Name = "Neighborhood";

            //Sales Total Amount
            pvt.AddDataField(pvt.PivotFields("Sold Price"), "Rank", Excel.XlConsolidationFunction.xlSum);
            pvt.PivotFields("Rank").Calculation = Excel.XlPivotFieldCalculation.xlRankDecending;
            pvt.PivotFields("Rank").BaseField   = RankBaseField;
            //Sort By Rank
            pvt.PivotFields(RankBaseField).AutoSort(2, "Rank");
            //Total Amount
            pvt.AddDataField(pvt.PivotFields("Sold Price"), "Total Sales Amount", Excel.XlConsolidationFunction.xlSum);
            pvt.PivotFields("Total Sales Amount").NumberFormat = "$#,##0";
            pvt.AddDataField(pvt.PivotFields("Sold Price"), "Market Share", Excel.XlConsolidationFunction.xlSum);
            pvt.PivotFields("Market Share").Calculation = Excel.XlPivotFieldCalculation.xlPercentOfTotal;
            //Sales Count
            pvt.AddDataField(pvt.PivotFields("Status"), "Sales", Excel.XlConsolidationFunction.xlCount);
            pvt.PivotFields("Sales").NumberFormat = "0";
            //Ave Sold Price
            pvt.AddDataField(pvt.PivotFields("Sold Price"), "Avg. Sold Price", Excel.XlConsolidationFunction.xlAverage);
            pvt.PivotFields("Avg. Sold Price").NumberFormat = "$#,##0";
            pvt.AddDataField(pvt.PivotFields("Sold Price"), "Avg. S.Price Rank", Excel.XlConsolidationFunction.xlAverage);
            pvt.PivotFields("Avg. S.Price Rank").Calculation = Excel.XlPivotFieldCalculation.xlRankDecending;
            pvt.PivotFields("Avg. S.Price Rank").BaseField   = RankBaseField;
            //Price Per SqFt
            pvt.AddDataField(pvt.PivotFields("SP Sqft"), "Avg. $PerSQFT", Excel.XlConsolidationFunction.xlAverage);
            pvt.PivotFields("Avg. $PerSQFT").NumberFormat = "$#,##0";
            pvt.AddDataField(pvt.PivotFields("SP Sqft"), "Avg. $PSF Rank", Excel.XlConsolidationFunction.xlAverage);
            pvt.PivotFields("Avg. $PSF Rank").Calculation = Excel.XlPivotFieldCalculation.xlRankDecending;
            pvt.PivotFields("Avg. $PSF Rank").BaseField   = RankBaseField;
            //Days On Market
            pvt.AddDataField(pvt.PivotFields("CDOM"), "Avg. Days OnMkt", Excel.XlConsolidationFunction.xlAverage);
            pvt.PivotFields("Avg. Days OnMkt").NumberFormat = "0";
            pvt.RowAxisLayout(Excel.XlLayoutRowType.xlTabularRow);
        }
예제 #8
0
        private static void outputReport()
        {
            int    row = 0, col = 0;
            string formatString;

            Excel.Application excelApp = new Excel.Application();
            if (excelApp == null)
            {
                MessageBox.Show("WANRNING!\n<< TRIED TO CREATE REPORT BUT EXCEL IS NOT INSTALLED! >>");
            }
            else
            {
                Excel.Workbook  workbook      = excelApp.Workbooks.Open(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Reports.xlsx");
                Excel.Worksheet DataWorksheet = workbook.Worksheets[workbook.Worksheets.Count];
                try
                {
                    DataWorksheet.Name = "Data";
                    DataTable data = DatabaseTools.getReportData();
                    foreach (DataColumn dataColumn in data.Columns)
                    {
                        DataWorksheet.Range["A1"].Offset[0, col].Value = dataColumn.ColumnName;
                        switch (dataColumn.DataType.ToString())
                        {
                        case "System.Decimal":
                            formatString = "_-[$£-en-GB]* #,##0.00_-;-[$£-en-GB]* #,##0.00_-;_-[$£-en-GB]* \" - \"??_-;_-@_-";
                            break;

                        case "System.Int32":
                            formatString = "0";
                            break;

                        case "System.DateTime":
                            formatString = "dd/mm/yyyy";
                            break;

                        default:
                            formatString = "@";
                            break;
                        }
                        DataWorksheet.Range["A1"].Offset[0, col].EntireColumn.NumberFormat = formatString;
                        col++;
                    }
                    row = 2;
                    foreach (DataRow dataRow in data.Rows)
                    {
                        for (col = 0; col < data.Columns.Count; col++)
                        {
                            DataWorksheet.Cells[row, col + 1] = dataRow[col] == DBNull.Value ? string.Empty : dataRow[col].ToString();
                        }
                        row++;
                    }
                    DataWorksheet.Columns.AutoFit();
                    Excel.Worksheet PivotSheet = workbook.Worksheets.Add();
                    PivotSheet.Name = DateTime.Now.ToLongDateString();

                    Excel.Range      dataRange = DataWorksheet.UsedRange;
                    Excel.PivotCache cache     = workbook.PivotCaches().Create(Excel.XlPivotTableSourceType.xlDatabase, dataRange);

                    Excel.PivotCaches pivotCaches = workbook.PivotCaches();
                    pivotCaches.Create(Excel.XlPivotTableSourceType.xlDatabase, dataRange).CreatePivotTable(PivotSheet.Cells[1, 1], "Table");
                    Excel.PivotTable pivotTable = PivotSheet.PivotTables("Table");

                    Excel.PivotField field = pivotTable.PivotFields("Job Name");
                    field.Orientation      = Excel.XlPivotFieldOrientation.xlRowField;
                    field.LayoutCompactRow = false;
                    field.Subtotals        = new bool[12] {
                        false, false, false, false, false, false, false, false, false, false, false, false
                    };

                    field             = pivotTable.PivotFields("Order Number");
                    field.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                    field.Subtotals   = new bool[12] {
                        false, false, false, false, false, false, false, false, false, false, false, false
                    };

                    field             = pivotTable.PivotFields("Total Value");
                    field.Orientation = Excel.XlPivotFieldOrientation.xlDataField;
                    field.Caption     = "Total Values";

                    field             = pivotTable.PivotFields("Average Value");
                    field.Orientation = Excel.XlPivotFieldOrientation.xlDataField;
                    field.Caption     = "Average Values";

                    PivotSheet.UsedRange.Columns.AutoFit();

                    pivotTable.MergeLabels   = true;
                    pivotTable.ShowValuesRow = false;

                    pivotTable.ColumnGrand = false;
                    pivotTable.RowGrand    = false;
                }
                catch (Exception e)
                {
                    MessageBox.Show(string.Format(e.Message + "\n" + e.InnerException + "\n" + e.Data));
                }
                finally
                {
                    workbook.Save();
                    workbook.Close();
                    excelApp.Quit();
                }
            }
        }
        private void GenerateReport()
        {
            #region Initialize
            Excel.Workbook    activeWorkBook = null;
            Excel.Worksheet   pivotWorkSheet = null;
            Excel.PivotCaches pivotCaches    = null;
            Excel.PivotCache  pivotCache     = null;
            Excel.PivotTable  pivotTable     = null;
            Excel.PivotFields pivotFields    = null;

            Excel.PivotField monthPivotField         = null;
            Excel.PivotField statusPivotField        = null;
            Excel.PivotField resolvedPivotField      = null;
            Excel.PivotField threatIdPivotField      = null;
            Excel.PivotField threatIdCountPivotField = null;

            Excel.SlicerCaches slicerCaches     = null;
            Excel.SlicerCache  monthSlicerCache = null;
            Excel.Slicers      monthSlicers     = null;
            Excel.Slicer       monthSlicer      = null;

            Excel.SlicerCache statusSlicerCache = null;
            Excel.Slicers     statusSlicers     = null;
            Excel.Slicer      statusSlicer      = null;

            Excel.SlicerCache resolvedSlicerCache = null;
            Excel.Slicers     resolvedSlicers     = null;
            Excel.Slicer      resolvedSlicer      = null;
            #endregion
            try
            {
                activeWorkBook = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.ActiveWorkbook;
                try
                {
                    pivotWorkSheet = (Excel.Worksheet)(ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.Worksheets.get_Item("Threat Reports");
                    (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.ActiveSheet.Application.DisplayAlerts = false;
                    pivotWorkSheet.Delete();
                    pivotWorkSheet      = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.ActiveWorkbook.Worksheets.Add() as Excel.Worksheet;
                    pivotWorkSheet.Name = "Agent Reports";
                    pivotWorkSheet.Activate();
                }
                catch
                {
                    pivotWorkSheet      = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.ActiveWorkbook.Worksheets.Add() as Excel.Worksheet;
                    pivotWorkSheet.Name = "Agent Reports";
                    pivotWorkSheet.Activate();
                }

                (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.ActiveWindow.DisplayGridlines = false;

                #region Create Headings
                // Create headings
                // =================================================================================================================
                Excel.Range title = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range("A1", "A1");
                title.ClearFormats();
                title.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(r_color, g_color, b_color));
                title.Font.Color     = System.Drawing.Color.White;
                title.InsertIndent(1);
                title.Font.Size         = 18;
                title.VerticalAlignment = -4108; // xlCenter

                Excel.Range titleRow = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range("A1", "CA1");
                titleRow.Select();
                titleRow.RowHeight      = 33;
                titleRow.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(r_color, g_color, b_color));
                (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.Cells[1, 1] = "Threat Reports";
                (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.Cells[2, 1] = "Generated by: " + userName;
                (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.Cells[3, 1] = DateTime.Now.ToString("f");

                Excel.Range rowSeparator = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range("A3", "CA3");
                rowSeparator.Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).Color     = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(r_color, g_color, b_color)); //
                rowSeparator.Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = 1;                                                                                              // xlContinuous
                rowSeparator.Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).Weight    = 4;                                                                                              // xlThick
                #endregion

                // Create the Pivot Table
                pivotCaches = activeWorkBook.PivotCaches();
                activeWorkBook.ShowPivotTableFieldList = false;
                // pivotCache = pivotCaches.Create(Excel.XlPivotTableSourceType.xlDatabase, "Threats!$A$4:$" + ExcelColumnLetter(colCount) + "$" + rowCount);
                // string rangeName = "Threats!$A$4:$T$100";
                string rangeName = "'Agent Data'!$A$4:$" + eHelper.ExcelColumnLetter(colCount - 1) + "$" + (rowCount + 4).ToString();
                pivotCache = pivotCaches.Create(Excel.XlPivotTableSourceType.xlDatabase, rangeName);
                // pivotTable = pivotCache.CreatePivotTable("Reports!R3C1");
                pivotTable            = pivotCache.CreatePivotTable("'Agent Reports'!R7C1");
                pivotTable.NullString = "0";

                // Set the Pivot Fields
                pivotFields = (Excel.PivotFields)pivotTable.PivotFields();

                // Month Pivot Field
                monthPivotField             = (Excel.PivotField)pivotFields.Item("Created Date");
                monthPivotField.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                monthPivotField.Position    = 1;
                monthPivotField.DataRange.Cells[1].Group(true, true, Type.Missing, new bool[] { false, false, false, false, true, true, true });

                // Mitigation Status Pivot Field
                statusPivotField             = (Excel.PivotField)pivotFields.Item("Mitigation Status");
                statusPivotField.Orientation = Excel.XlPivotFieldOrientation.xlColumnField;

                // Resolved Pivot Field
                resolvedPivotField             = (Excel.PivotField)pivotFields.Item("Resolved");
                resolvedPivotField.Orientation = Excel.XlPivotFieldOrientation.xlPageField;

                // Threat ID Pivot Field
                threatIdPivotField = (Excel.PivotField)pivotFields.Item("ID");

                // Count of Threat ID Field
                threatIdCountPivotField = pivotTable.AddDataField(threatIdPivotField, "# of Threats", Excel.XlConsolidationFunction.xlCount);

                slicerCaches = activeWorkBook.SlicerCaches;
                // Month Slicer
                monthSlicerCache = slicerCaches.Add(pivotTable, "Created Date", "CreatedDate");
                monthSlicers     = monthSlicerCache.Slicers;
                monthSlicer      = monthSlicers.Add((ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.ActiveSheet, Type.Missing, "Created Date", "Created Date", 80, 480, 144, 100);
                // Mitigation Status Slicer
                statusSlicerCache = slicerCaches.Add(pivotTable, "Mitigation Status", "MitigationStatus");
                statusSlicers     = statusSlicerCache.Slicers;
                statusSlicer      = statusSlicers.Add((ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.ActiveSheet, Type.Missing, "Mitigation Status", "Mitigation Status", 80, 634, 144, 100);
                // Resolved Slicer
                resolvedSlicerCache = slicerCaches.Add(pivotTable, "Resolved", "Resolved");
                resolvedSlicers     = resolvedSlicerCache.Slicers;
                resolvedSlicer      = resolvedSlicers.Add((ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.ActiveSheet, Type.Missing, "Resolved", "Resolved", 80, 788, 144, 100);
                // Slicer original sizes top 15, width 144, height 200
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error generating report", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                #region Finally
                if (resolvedSlicer != null)
                {
                    Marshal.ReleaseComObject(resolvedSlicer);
                }
                if (resolvedSlicers != null)
                {
                    Marshal.ReleaseComObject(resolvedSlicers);
                }
                if (resolvedSlicerCache != null)
                {
                    Marshal.ReleaseComObject(resolvedSlicerCache);
                }
                if (statusSlicer != null)
                {
                    Marshal.ReleaseComObject(statusSlicer);
                }
                if (statusSlicers != null)
                {
                    Marshal.ReleaseComObject(statusSlicers);
                }
                if (statusSlicerCache != null)
                {
                    Marshal.ReleaseComObject(statusSlicerCache);
                }
                if (monthSlicer != null)
                {
                    Marshal.ReleaseComObject(monthSlicer);
                }
                if (monthSlicers != null)
                {
                    Marshal.ReleaseComObject(monthSlicers);
                }
                if (monthSlicerCache != null)
                {
                    Marshal.ReleaseComObject(monthSlicerCache);
                }
                if (slicerCaches != null)
                {
                    Marshal.ReleaseComObject(slicerCaches);
                }
                if (threatIdCountPivotField != null)
                {
                    Marshal.ReleaseComObject(threatIdCountPivotField);
                }
                if (threatIdPivotField != null)
                {
                    Marshal.ReleaseComObject(threatIdPivotField);
                }
                if (resolvedPivotField != null)
                {
                    Marshal.ReleaseComObject(resolvedPivotField);
                }
                if (statusPivotField != null)
                {
                    Marshal.ReleaseComObject(statusPivotField);
                }
                if (monthPivotField != null)
                {
                    Marshal.ReleaseComObject(monthPivotField);
                }
                if (pivotFields != null)
                {
                    Marshal.ReleaseComObject(pivotFields);
                }
                if (pivotTable != null)
                {
                    Marshal.ReleaseComObject(pivotTable);
                }
                if (pivotCache != null)
                {
                    Marshal.ReleaseComObject(pivotCache);
                }
                if (pivotCaches != null)
                {
                    Marshal.ReleaseComObject(pivotCaches);
                }
                if (pivotWorkSheet != null)
                {
                    Marshal.ReleaseComObject(pivotWorkSheet);
                }
                if (activeWorkBook != null)
                {
                    Marshal.ReleaseComObject(activeWorkBook);
                }
                #endregion
            }
        }