示例#1
0
        private void SaveDataTableToWorksheet(DataTable dt, ExcelWorksheet ws, bool autoFitColumns)
        {
            if (dt.Rows.Count > 0)
            {
                ExcelRangeBase range = ws.Cells["A2"].LoadFromDataTable(dt, true);

                ws.Row(2).Style.Font.Bold = true;

                // find all datetime columns and set formatting
                int numcols = dt.Columns.Count;
                for (int i = 0; i < numcols; i++)
                {
                    var column = dt.Columns[i];
                    if (column.DataType == typeof(DateTime))
                    {
                        ws.Column(i + 1).Style.Numberformat.Format = "yyyy-mm-dd hh:MM:ss";
                    }
                }

                if (autoFitColumns)
                {
                    range.AutoFitColumns();
                }
            }
            else
            {
                ws.Cells["A2"].Value = "None Found";
            }
        }
        private void BaseDeDatos(string filePath, ExcelPackage excelPackage, ExcelRangeBase excelRangeBase, ExcelWorksheet excelWorksheet)
        {
            //int nextRow = excelRangeBase.End.Row + 1;
            //TODO: el idioma...
            excelPackage.Workbook.Worksheets["MATRIZ"].Cells["K1"].Value = DateTime.Now.AddDays(-1).ToString("MMMM", CultureInfo.GetCultureInfo("es-PE"));

            excelWorksheet.Cells[1, excelRangeBase.End.Column + 1].Value = "CONCATENADO";
            excelWorksheet.Cells[1, excelRangeBase.End.Column + 2].Value = "CODIGO";

            excelWorksheet.Cells[2, excelRangeBase.End.Column + 1, excelRangeBase.End.Row + 1, excelRangeBase.End.Column + 1].Formula = "G2&H2&I2";
            excelWorksheet.Cells[2, excelRangeBase.End.Column + 1, excelRangeBase.End.Row + 1, excelRangeBase.End.Column + +1].Calculate();

            //El separador de parámetros de fórmula es ',' por que se usa la notación en inglés, igualmente con las formulas.
            excelWorksheet.Cells[2, excelRangeBase.End.Column + 2, excelRangeBase.End.Row + 1, excelRangeBase.End.Column + 2].Formula = "VLOOKUP(U2,CONCATENADO!$D$2:$E$304,2,0)";
            //excelWorksheet.Cells[2, excelRangeBase.End.Column + 2, excelRangeBase.End.Row + 1, excelRangeBase.End.Column + 2].FormulaR1C1 = "VLOOKUP(U2,CONCATENADO!$D$2:$E$304,2,0)";
            excelWorksheet.Cells[2, excelRangeBase.End.Column + 2, excelRangeBase.End.Row + 1, excelRangeBase.End.Column + 2].Calculate();


            //TODO: take a look in future for performance decrease
            excelRangeBase.AutoFitColumns();

            excelPackage.Save();

            DataTable sheetData = GetDataExcel(filePath,
                                               "SELECT  CODIGO,CANT_OPERACIONES FROM (SELECT CODIGO,SUM(CANT_OPERACIONES) AS CANT_OPERACIONES " +
                                               "FROM [BASE$] GROUP BY CODIGO) A " +
                                               "RIGHT JOIN [MATRIZ$] B " +
                                               "ON A.CODIGO = B.JEDOX");


            excelPackage.Workbook.Worksheets["MATRIZ"].Cells[sheetData.Rows.Count + 3, 10].Value = "TOTAL:";

            for (int i = 0; i <= sheetData.Rows.Count - 1; i++)
            {
                //if(sheetData.Rows[i]["CANT_OPERACIONES"] == DBNull.Value ? 0: Convert.ToDecimal(sheetData.Rows[i]["CANT_OPERACIONES"])
                //    9

                excelPackage.Workbook.Worksheets["MATRIZ"].Cells["K" + (i + 2)].Value =
                    sheetData.Rows[i]["CANT_OPERACIONES"] == DBNull.Value ? 0 : Convert.ToDecimal(sheetData.Rows[i]["CANT_OPERACIONES"]);
                //sheetData.Rows[i]["CANT_OPERACIONES"];
            }

            excelPackage.Workbook.Worksheets["MATRIZ"].Cells[sheetData.Rows.Count + 3, 11].Formula = "SUM(K2:K" + (sheetData.Rows.Count + 1) + ")";
            excelPackage.Workbook.Worksheets["MATRIZ"].Cells[sheetData.Rows.Count + 3, 11].Calculate();

            //excelWorksheet.Cells[nextRow, 4, nextRow, column].Formula = "SUM(E2:E10)";
            //excelWorksheet.Cells[nextRow, 5, nextRow, column].Calculate();

            excelPackage.Save();
            //return sheetData;

            //TOTAL	18344	18344
        }
        private static async Task DynamicDateAugustFilter(string connectionString, ExcelPackage p)
        {
            var            ws    = p.Workbook.Worksheets.Add("DynamicAugustFilter");
            ExcelRangeBase range = await LoadFromDatabase(connectionString, ws);

            range.AutoFilter = true;
            var colDynamic = ws.AutoFilter.Columns.AddDynamicFilterColumn(5);

            colDynamic.Type = eDynamicFilterType.M8;
            ws.AutoFilter.ApplyFilter();
            range.AutoFitColumns(0);
        }
        internal static void FormatAsTable(ExcelRangeBase range, TableStyles tableStyle, string tableName, bool autoFitColumns = true)
        {
            //format the table
            var table = range.Worksheet.Tables.Add(range, tableName);

            table.TableStyle = tableStyle;

            if (autoFitColumns)
            {
                range.AutoFitColumns();
            }
        }
        private static async Task ValueFilter(string connectionString, ExcelPackage p)
        {
            var            ws    = p.Workbook.Worksheets.Add("ValueFilter");
            ExcelRangeBase range = await LoadFromDatabase(connectionString, ws);

            range.AutoFilter = true;
            var colCompany = ws.AutoFilter.Columns.AddValueFilterColumn(0);

            colCompany.Filters.Add("Walsh LLC");
            colCompany.Filters.Add("Harber-Goldner");
            ws.AutoFilter.ApplyFilter();
            range.AutoFitColumns(0);
        }
示例#6
0
        public static bool Export(List <Patient> patients, string path, string name, List <PatientExportParams> @params)
        {
            try
            {
                FileInfo file = new(path + "\\" + name + ".xlsx");
                if (file.Exists)
                {
                    try { file.Delete(); } catch { return(false); }
                }
                ;

                ExcelPackage package = new(file);

                ExcelWorksheet ws = package.Workbook.Worksheets.Add("patients");
                ws.Cells[1, 1].LoadFromCollection <Patient>(patients, true);
                ws.Cells[1, 8].LoadFromCollection <PatientData>(new List <PatientData>(), true);
                for (int i = 2, j = 0; j < patients.Count; j++)
                {
                    ws.InsertRow(i + 1, patients[j].PatientDataList.Count - 1);
                    package.Save();

                    ws.Cells[i, 8].LoadFromCollection(patients[j].PatientDataList, false);

                    i += patients[j].PatientDataList.Count;
                }

                ExcelRangeBase range = ws.Cells;
                range.AutoFitColumns();

                ws.DeleteColumn(1);
                for (int i = 0, j = 1; i < 16; i++)
                {
                    if (!@params[i].IsShown)
                    {
                        ws.DeleteColumn(j);
                    }
                    else
                    {
                        j++;
                    }
                }

                package.Save();

                return(true);
            }
            catch
            {
                return(false);
            }
        }
        private static async Task Top10Filter(string connectionString, ExcelPackage p)
        {
            var            ws    = p.Workbook.Worksheets.Add("Top10Filter");
            ExcelRangeBase range = await LoadFromDatabase(connectionString, ws);

            range.AutoFilter = true;
            var colTop10 = ws.AutoFilter.Columns.AddTop10FilterColumn(6);

            colTop10.Percent = false;    //If set to true, the value takes top the percentage. Otherwise it relates to the number of items.
            colTop10.Value   = 10;       //The value to relate to.
            colTop10.Top     = false;    //Top if true, bottom if false
            ws.AutoFilter.ApplyFilter();
            range.AutoFitColumns(0);
        }
        private static async Task CustomFilter(string connectionString, ExcelPackage p)
        {
            var            ws    = p.Workbook.Worksheets.Add("CustomFilter");
            ExcelRangeBase range = await LoadFromDatabase(connectionString, ws);

            range.AutoFilter = true;
            var colCompany = ws.AutoFilter.Columns.AddCustomFilterColumn(6);

            colCompany.And = true;
            colCompany.Filters.Add(new ExcelFilterCustomItem("999.99", eFilterOperator.GreaterThan));
            colCompany.Filters.Add(new ExcelFilterCustomItem("1500", eFilterOperator.LessThanOrEqual));
            ws.AutoFilter.ApplyFilter();
            range.AutoFitColumns(0);
        }
        private static async Task DateTimeFilter(string connectionString, ExcelPackage p)
        {
            var            ws    = p.Workbook.Worksheets.Add("DateTimeFilter");
            ExcelRangeBase range = await LoadFromDatabase(connectionString, ws);

            range.AutoFilter = true;
            var col = ws.AutoFilter.Columns.AddValueFilterColumn(5);

            col.Filters.Add(new ExcelFilterDateGroupItem(2017, 8));
            col.Filters.Add(new ExcelFilterDateGroupItem(2017, 7, 5));
            col.Filters.Add(new ExcelFilterDateGroupItem(2017, 7, 7));
            ws.AutoFilter.ApplyFilter();
            range.AutoFitColumns(0);
        }
        internal static void FormatAsTable(ExcelRangeBase range, TableStyles tableStyle, string tableName, bool autoFitColumns = true)
        {
            string escapedTableName = ExcelAddressUtil.GetValidName(tableName);

            //format the table
            var table = range.Worksheet.Tables.Add(range, escapedTableName);

            table.TableStyle = tableStyle;

            if (autoFitColumns)
            {
                range.AutoFitColumns();
            }
        }
        private static async Task PivotTableFilter(string connectionString, ExcelPackage p)
        {
            var            ws    = p.Workbook.Worksheets.Add("PivotTableFilter");
            ExcelRangeBase range = await LoadFromDatabase(connectionString, ws);

            var tbl = ws.Tables.Add(range, "ptFilter");

            tbl.TableStyle = OfficeOpenXml.Table.TableStyles.Medium23;

            var pt1       = ws.PivotTables.Add(ws.Cells["J1"], tbl, "PivotTable1");
            var rowField  = pt1.RowFields.Add(pt1.Fields["CompanyName"]);
            var dataField = pt1.DataFields.Add(pt1.Fields["OrderValue"]);

            //First deselect a company in the items list. To do so we first need to refresh the items from the range.
            rowField.Items.Refresh();  //Refresh the items from the range.
            rowField.Items.GetByValue("Sporer, Mertz and Jaskolski").Hidden = true;
            //Add a caption filter on Company Name between A and D
            rowField.Filters.AddCaptionFilter(ePivotTableCaptionFilterType.CaptionBetween, "A", "D");
            //Add a value filter where OrderValue >= 100
            rowField.Filters.AddValueFilter(ePivotTableValueFilterType.ValueGreaterThanOrEqual, dataField, 100);

            //Add a second pivot table with some different filters.
            var pt2       = ws.PivotTables.Add(ws.Cells["M1"], tbl, "PivotTable2");
            var rowField1 = pt2.RowFields.Add(pt2.Fields["Currency"]);
            var rowField2 = pt2.RowFields.Add(pt2.Fields["OrderDate"]);

            rowField2.Format = "yyyy-MM-dd";
            var dataField1 = pt2.DataFields.Add(pt2.Fields["OrderValue"]);
            var dataField2 = pt2.DataFields.Add(pt2.Fields["OrderId"]);

            dataField2.Function = DataFieldFunctions.CountNums;

            var slicer = rowField1.AddSlicer();

            slicer.SetPosition(11, 0, 9, 0);
            //Add a date filter between first of Mars 2017 to 30th of June
            rowField2.Filters.AddDateValueFilter(ePivotTableDateValueFilterType.DateBetween, new DateTime(2017, 3, 1), new DateTime(2017, 6, 30));
            //Add a filter on the bottom 25 percent of the OrderValue
            rowField2.Filters.AddTop10Filter(ePivotTableTop10FilterType.Percent, dataField1, 25, false);
            pt2.DataOnRows = false;

            range.AutoFitColumns(0);
        }
        private static async Task TableFilter(string connectionString, ExcelPackage p)
        {
            var            ws    = p.Workbook.Worksheets.Add("TableFilter");
            ExcelRangeBase range = await LoadFromDatabase(connectionString, ws);

            var tbl = ws.Tables.Add(range, "tblFilter");

            tbl.TableStyle = OfficeOpenXml.Table.TableStyles.Medium23;
            tbl.ShowFilter = true;
            //Add a value filter
            var colCompany = tbl.AutoFilter.Columns.AddValueFilterColumn(0);

            colCompany.Filters.Add("Walsh LLC");
            colCompany.Filters.Add("Harber-Goldner");
            colCompany.Filters.Add("Sporer, Mertz and Jaskolski");

            //Add a second filter on order value
            var colOrderValue = tbl.AutoFilter.Columns.AddCustomFilterColumn(6);

            colOrderValue.Filters.Add(new ExcelFilterCustomItem("500", eFilterOperator.GreaterThanOrEqual));
            tbl.AutoFilter.ApplyFilter();
            range.AutoFitColumns(0);
        }
示例#13
0
        private void Generar_Excel()
        {
            SaveFileDialog Sfd_Ruta_Archivo = new SaveFileDialog();
            DataTable      Dt_General       = Grd_Resultados.DataSource as DataTable;

            try
            {
                Dt_General.TableName = "Padre";
                if (Cmb_Tipo_Reporte.SelectedIndex == 2 ||
                    Cmb_Tipo_Reporte.SelectedIndex == 3)
                {
                    Dt_General.Rows.RemoveAt(Dt_General.Rows.Count - 1);
                }

                //  se obtiene la ruta del archivo
                Sfd_Ruta_Archivo.Filter           = "Excel (*.xlsx)|*.xlsx";
                Sfd_Ruta_Archivo.FilterIndex      = 0;
                Sfd_Ruta_Archivo.RestoreDirectory = true;

                //  validacion a la ruta del archivo
                if (Sfd_Ruta_Archivo.ShowDialog() == DialogResult.OK)
                {
                    if (File.Exists(Sfd_Ruta_Archivo.FileName))
                    {
                        File.Delete(Sfd_Ruta_Archivo.FileName);
                    }
                    FileInfo newFile = new FileInfo(Sfd_Ruta_Archivo.FileName);

                    using (ExcelPackage Anual = new ExcelPackage(newFile))
                    {
                        ExcelWorksheet Detallado = Anual.Workbook.Worksheets.Add("Analisis_Anual");
                        string         Letra_Fin = ((char)(65 + Dt_General.Columns.Count - 1)).ToString();
                        string         EFiltros  = (string)Filtros()[1];

                        Detallado.Cells["A1"].Value = "Tesorería Municipal";
                        Detallado.Cells["A2"].Value = "Dirección de ingresos";
                        Detallado.Cells["A3"].Value = "Museo de las Momias";
                        Detallado.Cells["A4"].Value = "Periodo: De " + Cmb_Anio_Inicial.Text + " al " + Cmb_Anio_Final.Text;
                        Detallado.Cells["A5"].Value = EFiltros;

                        Detallado.Cells["A1:" + Letra_Fin + "5"].Style.Font.Bold = true;

                        // Encabezados del reporte
                        Detallado.Cells["A1:" + Letra_Fin + "1"].Merge = true;
                        Detallado.Cells["A2:" + Letra_Fin + "2"].Merge = true;
                        Detallado.Cells["A3:" + Letra_Fin + "3"].Merge = true;
                        Detallado.Cells["A4:" + Letra_Fin + "4"].Merge = true;
                        Detallado.Cells["A5:" + Letra_Fin + "5"].Merge = true;

                        Detallado.Cells["A1:" + Letra_Fin + "1"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                        Detallado.Cells["A2:" + Letra_Fin + "2"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                        Detallado.Cells["A3:" + Letra_Fin + "3"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                        Detallado.Cells["A4:" + Letra_Fin + "4"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                        Detallado.Cells["A5:" + Letra_Fin + "5"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                        Detallado.Cells["A1:" + Letra_Fin + "1"].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                        Detallado.Cells["A2:" + Letra_Fin + "2"].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                        Detallado.Cells["A3:" + Letra_Fin + "3"].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                        Detallado.Cells["A4:" + Letra_Fin + "4"].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                        Detallado.Cells["A5:" + Letra_Fin + "5"].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;

                        // Se carga la información del DataTable en la Hoja de Excel.
                        ExcelRangeBase Rango = Detallado.Cells["A7"].LoadFromDataTable(Dt_General,
                                                                                       true, OfficeOpenXml.Table.TableStyles.Medium2);

                        // Se generan los Totales;
                        if (Cmb_Tipo_Reporte.SelectedIndex == 2 ||
                            Cmb_Tipo_Reporte.SelectedIndex == 3)
                        {
                            int C = (int)'A';
                            for (int i = 1; i < Dt_General.Columns.Count; i++)
                            {
                                string Column = Dt_General.Columns[i].ColumnName;
                                string cell   = (char)(C + i) + (Rango.End.Row + 1).ToString();

                                Detallado.Cells[cell].Formula = "SUM(Padre[" + Column + "])";
                            }
                        }

                        if (Cmb_Tipo_Reporte.SelectedIndex == 1 ||
                            Cmb_Tipo_Reporte.SelectedIndex == 2)
                        {
                            Detallado.Cells[8, 1, Rango.End.Row + 1, Rango.End.Column]
                            .Style.Numberformat.Format = "#,##0.00";
                        }

                        if (Cmb_Tipo_Reporte.Text.Equals("Concentrado"))
                        {
                            Detallado.Cells[Rango.End.Row - 1, 1, Rango.End.Row - 1, Rango.End.Column]
                            .Style.Numberformat.Format = "#,##0.00";
                        }

                        Rango.AutoFitColumns();

                        int Fila = Rango.End.Row + 1;


                        //  generacion de graficas
                        if (Cmb_Tipo_Reporte.SelectedIndex == 2 ||
                            Cmb_Tipo_Reporte.SelectedIndex == 3)
                        {
                            int Letter = (int)'B';
                            for (int i = 1; i < Dt_General.Columns.Count; i++)
                            {
                                string         Nombre = Dt_General.Columns[i].ColumnName;
                                ExcelWorksheet Graph  = Anual.Workbook.Worksheets.Add(Nombre);

                                var chart = Graph.Drawings.AddChart(Nombre,
                                                                    OfficeOpenXml.Drawing.Chart.eChartType.ColumnClustered);

                                chart.SetPosition(0, 0, 0, 0);
                                chart.SetSize(1280, 800);

                                for (int j = 8; j <= Rango.End.Row; j++)
                                {
                                    int Column = i + 1;
                                    if (Detallado.Cells[j, Column, j, Column].Value != null)
                                    {
                                        string Cell   = ((char)Letter).ToString();
                                        string Adress = "Analisis_Anual!$" + Cell + "$" + j + ":$"
                                                        + Cell + "$" + j;

                                        chart.Series.Add(Adress,
                                                         "Analisis_Anual!$" + Cell + "$7:$" + Cell + "$7")
                                        .Header = Detallado.Cells["A" + j].Value.ToString();
                                    }
                                }

                                chart.Title.Text = "Análisis Anual " + Nombre;
                                Letter++;
                            }
                        }

                        Anual.Save();
                    }

                    MessageBox.Show("Archivo Guardado Correctamente", "Éxito",
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// Evento que genera el reporte de concentrado de las ventas.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <creo>Juan Alberto Hernández Negrete</creo>
        /// <fecha_creo>2014 05 22 09:50 Hrs.</fecha_creo>
        /// <modifico></modifico>
        /// <fecha_modifico></fecha_modifico>
        /// <causa_modificacion></causa_modificacion>
        private void Btn_Exportar_Excel_Click(object sender, EventArgs e)
        {
            DataSet        Ds_Resultados_Busqueda = null;//Variable que utilizaremos para almacenar los resultados de la búsqueda.
            SaveFileDialog Sfd_Ruta_Archivo       = new SaveFileDialog();
            DataTable      Dt_Cancelaciones       = new DataTable();
            DataTable      Dt_General             = new DataTable();
            Int32          Cont_Registros         = 0;

            try
            {
                //  realiza la consulta de la informacion
                Ds_Resultados_Busqueda = Consultar_DsReporte();

                Dt_Cancelaciones = Ds_Resultados_Busqueda.Tables["Detalle_Ventas"];
                Dt_General       = Ds_Resultados_Busqueda.Tables["Datos_Generales"];

                //  se obtiene la ruta del archivo
                Sfd_Ruta_Archivo.Filter           = "Execl files (*.xlsx)|*.xlsx";
                Sfd_Ruta_Archivo.FilterIndex      = 0;
                Sfd_Ruta_Archivo.RestoreDirectory = true;

                //  se cambiaran los nombres de ñas columnas
                foreach (DataColumn Dc_Registro in Dt_Cancelaciones.Columns)
                {
                    Dc_Registro.ColumnName = Dc_Registro.ColumnName.Replace('_', ' ');
                }

                //  se cambia el nombre de la columna Fecha
                Dt_Cancelaciones.Columns["Fecha"].ColumnName = "Fecha_";
                Dt_Cancelaciones.Columns.Add("Fecha", typeof(System.DateTime));

                foreach (DataRow Dr_Registro in Dt_Cancelaciones.Rows)
                {
                    Dr_Registro["Fecha"] = Convert.ToDateTime(Dr_Registro["Fecha_"].ToString());
                }

                //  se remueve la columna de fecha_
                Dt_Cancelaciones.Columns.RemoveAt(6);

                //  validacion a la ruta del archivo
                if (Sfd_Ruta_Archivo.ShowDialog() == DialogResult.OK)
                {
                    if (File.Exists(Sfd_Ruta_Archivo.FileName))
                    {
                        File.Delete(Sfd_Ruta_Archivo.FileName);
                    }
                    FileInfo newFile = new FileInfo(Sfd_Ruta_Archivo.FileName);

                    //  obtenemos el numero de registros que se ingresaran
                    Cont_Registros = Dt_Cancelaciones.Rows.Count;

                    using (ExcelPackage Epc_Accesos = new ExcelPackage(newFile))
                    {
                        ExcelWorksheet Detallado = Epc_Accesos.Workbook.Worksheets.Add("Folios cancelados");

                        //  orden de las columnas
                        Dt_Cancelaciones.Columns["Folio del ticket de venta"].SetOrdinal(0);
                        Dt_Cancelaciones.Columns["Folio del acceso Numero Inicial"].SetOrdinal(1);
                        Dt_Cancelaciones.Columns["Folio del acceso Numero Final"].SetOrdinal(2);
                        Dt_Cancelaciones.Columns["Total Accesos"].SetOrdinal(3);
                        Dt_Cancelaciones.Columns["Importe total Ticket"].SetOrdinal(4);
                        Dt_Cancelaciones.Columns["Lugar de la venta"].SetOrdinal(5);
                        Dt_Cancelaciones.Columns["Fecha"].SetOrdinal(6);
                        Dt_Cancelaciones.Columns["Hora"].SetOrdinal(7);
                        Dt_Cancelaciones.Columns["Usuario Cancelo"].SetOrdinal(8);
                        Dt_Cancelaciones.Columns["Motivo Cancelacion"].SetOrdinal(9);


                        Detallado.Cells["A1"].Value = "Tesoreria Municipal";
                        Detallado.Cells["A2"].Value = "Dirección de ingresos";
                        Detallado.Cells["A3"].Value = "Museo de las momias";
                        Detallado.Cells["A4"].Value = Dt_General.Rows[0]["Periodo_Reporte"].ToString();
                        Detallado.Cells["A6"].Value = "Folios cancelados";


                        Detallado.Cells["A1:A1"].Style.Font.Bold = true;
                        Detallado.Cells["A3:A6"].Style.Font.Bold = true;


                        // Encabezados del reporte
                        Detallado.Cells["A1:J1"].Merge = true;
                        Detallado.Cells["A2:J2"].Merge = true;
                        Detallado.Cells["A3:J3"].Merge = true;
                        Detallado.Cells["A4:J4"].Merge = true;
                        Detallado.Cells["A6:J6"].Merge = true;

                        Detallado.Cells["A1:J1"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                        Detallado.Cells["A2:J2"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                        Detallado.Cells["A3:J3"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                        Detallado.Cells["A4:J4"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                        Detallado.Cells["A6:J6"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                        Detallado.Cells["A1:J1"].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                        Detallado.Cells["A2:J2"].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                        Detallado.Cells["A3:J3"].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                        Detallado.Cells["A4:J4"].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                        Detallado.Cells["A6:J6"].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;

                        //  se carga el archivo
                        ExcelRangeBase Rango = Detallado.Cells["A7"].LoadFromDataTable(Dt_Cancelaciones,
                                                                                       true, OfficeOpenXml.Table.TableStyles.Medium2);


                        Int32 Filas = 0;
                        Filas = Filas + Dt_Cancelaciones.Rows.Count + 8;

                        //  formato a las celdas
                        Detallado.Cells[7, 7, Rango.End.Row, 7].Style.Numberformat.Format = "mm-dd-yy";
                        Detallado.Cells[7, 4, Rango.End.Row, 4].Style.Numberformat.Format = "#,##0";
                        Detallado.Cells[7, 5, Rango.End.Row, 5].Style.Numberformat.Format = "#,##0.00";

                        //  subtotal
                        Detallado.Cells["D" + (Filas)].Formula = string.Format("SUBTOTAL(109, " + Dt_Cancelaciones.TableName + "[Total Accesos] )");
                        Detallado.Cells["E" + (Filas)].Formula = string.Format("SUBTOTAL(109, " + Dt_Cancelaciones.TableName + "[Importe total Ticket] )");
                        Detallado.Cells["D" + (Filas) + ":E" + (Filas)].Style.Font.Bold   = true;
                        Detallado.Cells[(Filas), 4, (Filas), 4].Style.Numberformat.Format = "#,##0";
                        Detallado.Cells[(Filas), 5, (Filas), 5].Style.Numberformat.Format = "#,##0.00";

                        Filas = Filas + 2;

                        //  pie de pagina
                        Detallado.Cells["A" + Filas.ToString()].Value       = "Usuario: " + MDI_Frm_Apl_Principal.Nombre_Usuario;
                        Detallado.Cells["A" + (Filas + 1).ToString()].Value = "Fecha de emisión: " + DateTime.Now.ToLongDateString() + "; " + DateTime.Now.ToLongTimeString();


                        Rango.AutoFitColumns();
                        Epc_Accesos.Save();
                    }


                    MessageBox.Show(this, "Exportacion exitosa", "Excel", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(this, Ex.Message, "Error - Método: [Btn_Consultar_Click]", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
示例#15
0
        /// <summary>
        /// Método que exporta el reporte a excel.
        /// </summary>
        /// <param name="Dt_Datos">Tabla que contiene los datos que se mostraran en el reporte</param>
        /// <param name="Titulo">Titulo del reporte</param>
        /// <creo>Juan Alberto Hernández Negrete</creo>
        /// <fecha_creo>21 Mayo 2014 10:08 Hrs</fecha_creo>
        /// <modifico></modifico>
        /// <fecha_modifico></fecha_modifico>
        /// <causa_modificacion></causa_modificacion>
        public void Exportar_Excel_Epplus(DataTable Dt_Datos, string Titulo)
        {
            SaveFileDialog Sfd_Ruta_Archivo = new SaveFileDialog();
            DataTable      Dt_General       = new DataTable();

            try
            {
                Dt_General = Dt_Datos.Copy();
                //  se obtiene la ruta del archivo
                Sfd_Ruta_Archivo.Filter           = "Execl files (*.xlsx)|*.xlsx";
                Sfd_Ruta_Archivo.FilterIndex      = 0;
                Sfd_Ruta_Archivo.RestoreDirectory = true;

                //  validacion a la ruta del archivo
                if (Sfd_Ruta_Archivo.ShowDialog() == DialogResult.OK)
                {
                    if (File.Exists(Sfd_Ruta_Archivo.FileName))
                    {
                        File.Delete(Sfd_Ruta_Archivo.FileName);
                    }
                    FileInfo newFile = new FileInfo(Sfd_Ruta_Archivo.FileName);

                    string Filtros = string.Empty;

                    if (Cmb_Turnos.SelectedIndex > 0)
                    {
                        Filtros += "Turno: " + Cmb_Turnos.Text + ", ";
                    }

                    if (Cmb_Cajas.SelectedIndex > 0)
                    {
                        Filtros += "No. Caja: " + Cmb_Cajas.Text + ", ";
                    }

                    if (Cmb_Lugar_Venta.SelectedIndex > 0)
                    {
                        if (Cmb_Lugar_Venta.Text.Equals("No Caja"))
                        {
                            Filtros += "Lugar Venta: Número de Caja, ";
                        }
                        else
                        {
                            Filtros += "Lugar Venta: " + Cmb_Lugar_Venta.Text + ", ";
                        }
                    }

                    if (Cmb_Museo.SelectedIndex > 0)
                    {
                        Filtros += "Museo: " + Cmb_Museo.Text + ", ";
                    }

                    if (!string.IsNullOrEmpty(Txt_Folio_Venta.Text))
                    {
                        Filtros += "Folio: " + Txt_Folio_Venta.Text + ", ";
                    }

                    if (Cmb_Producto.SelectedIndex > 0)
                    {
                        Filtros += "Tarifa: " + Cmb_Producto.Text + ", ";
                    }

                    using (ExcelPackage Epc_Accesos = new ExcelPackage(newFile))
                    {
                        ExcelWorksheet Detallado = Epc_Accesos.Workbook.Worksheets.Add("Ventas");

                        Detallado.Cells["A1"].Value = "Tesorería Municipal";
                        Detallado.Cells["A2"].Value = "Dirección de ingresos";
                        Detallado.Cells["A3"].Value = "Museo de las Momias";
                        Detallado.Cells["A4"].Value = "Periodo: De " + Dtp_Fecha_Inicio.Value.ToLongDateString() + " al " + Dtp_Fecha_Termino.Value.ToLongDateString();

                        if (!string.IsNullOrEmpty(Filtros))
                        {
                            string Aux = Filtros.Trim().Substring(0, Filtros.Trim().Length - 1);
                            Detallado.Cells["A5"].Value = Aux;
                        }

                        Detallado.Cells["A1:J5"].Style.Font.Bold = true;

                        // Encabezados del reporte
                        Detallado.Cells["A1:J1"].Merge = true;
                        Detallado.Cells["A2:J2"].Merge = true;
                        Detallado.Cells["A3:J3"].Merge = true;
                        Detallado.Cells["A4:J4"].Merge = true;
                        Detallado.Cells["A5:J5"].Merge = true;

                        Detallado.Cells["A1:J1"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                        Detallado.Cells["A2:J2"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                        Detallado.Cells["A3:J3"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                        Detallado.Cells["A4:J4"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                        Detallado.Cells["A5:J5"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                        Detallado.Cells["A1:J1"].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                        Detallado.Cells["A2:J2"].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                        Detallado.Cells["A3:J3"].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                        Detallado.Cells["A4:J4"].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                        Detallado.Cells["A5:J5"].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;

                        Dt_General.Columns[0].ColumnName = "Folio del Ticket de Venta";
                        Dt_General.Columns[1].ColumnName = "Fecha de Expedición";
                        Dt_General.Columns[2].ColumnName = "Tarifa";
                        Dt_General.Columns[8].ColumnName = "Lugar Venta";

                        //  se carga el archivo
                        Dt_General.Rows.RemoveAt(Dt_General.Rows.Count - 1);
                        ExcelRangeBase Rango = Detallado.Cells["A7"].LoadFromDataTable(Dt_General,
                                                                                       true, OfficeOpenXml.Table.TableStyles.Medium2);

                        // Formato de Fechas
                        Detallado.Cells[8, 2, Rango.End.Row, 2].Style.Numberformat.Format = "mm-dd-yy";

                        int Fila = Rango.End.Row + 1;

                        Detallado.Cells["E" + Fila].Formula = "SUM(Padre[Subtotal])";
                        Detallado.Cells["F" + Fila].Formula = "SUM(Padre[Descuentos])";
                        Detallado.Cells["G" + Fila].Formula = "SUM(Padre[Total])";

                        // Formato de Moneda
                        Detallado.Cells[8, 5, Fila, 7].Style.Numberformat.Format = "#,##0.00";

                        Fila += 2;
                        Detallado.Cells["A" + Fila.ToString()].Value       = "Usuario: " + MDI_Frm_Apl_Principal.Nombre_Usuario;
                        Detallado.Cells["A" + (Fila + 1).ToString()].Value = "Fecha de emisión: " + DateTime.Now.ToLongDateString() + "; " + DateTime.Now.ToLongTimeString();

                        Rango.AutoFitColumns();
                        Epc_Accesos.Save();

                        MessageBox.Show("Archivo Guardado Correctamente", "Éxito",
                                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(this, Ex.Message, "Error - Método: [Exportar_Excel_Epplus]", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }