/// <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)
            {
            }
        }
Ejemplo n.º 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();
        }
Ejemplo n.º 3
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);
        }
Ejemplo n.º 4
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);
            }
        }