1

Colegas, tengo el siguiente problema:

Actualmente estoy construyendo un método genérico que exporte datos a Excel. Entre los parámetros que le envío a dicha función se encuentran el encabezado, los datos y el nombre del archivo

private bool CreateExcel(IEnumerable headers, IEnumerable list, string fileName)

Hice las correspondientes pruebas y funciona perfecto. El problema es que estoy obteniendo las propiedades de dicha clase CourseToExcel mediante `PropertyDescriptorCollection, pero como pudieron notar estoy pasando la clase CourseToExcel de forma explícita.

Lo que necesito es pasar ese parámetro de forma dinámica para que acepte una clase con cualquier estructura y al mismo tiempo no tener conflictos al obtener las propiedades de dicha clase genérica.

Adjunto el método completo para quien lo necesite:

private bool CreateExcel(IEnumerable<string> headers, IEnumerable<CourseToExcel> list, string fileName)
        {
            try
            {
                using (ExcelPackage excel = new ExcelPackage())
                {
                    excel.Workbook.Worksheets.Add("Detalles");
                    ExcelWorksheet sheet = excel.Workbook.Worksheets["Detalles"];

                    #region HEADER
                    int posHeader = 1;
                    foreach(string header in headers)
                    {
                        sheet.Cells[1, posHeader].Value = header;
                        sheet.Cells[1, posHeader].Style.Font.Bold = true;
                        posHeader++;
                    }
                    #endregion

                    #region ROWS
                    int posRow = 2;
                    int col = 0;

                    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(CourseToExcel));

                    foreach (PropertyDescriptor p in properties)
                    {
                        col++;
                        foreach (var item in list.Select(x => p.GetValue(x)).ToList())
                        {
                            sheet.Cells[posRow, col].Value = item;
                            posRow++;
                        }
                        posRow = 2;
                    }
                    #endregion

                    sheet.Cells[sheet.Dimension.Address].AutoFitColumns();

                    FileInfo excelFile = new FileInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), $"{fileName}.xlsx"));
                    excel.SaveAs(excelFile);
                }
                return true;
            }
            catch(Exception e)
            {
                throw new Exception(e.Message);
            }
        }

Como siempre, cualquier información se agradece.

1 respuesta 1

3
 private bool CreateExcel<T>(IEnumerable<string> headers, IEnumerable<T> list, string fileName)
    {
        try
        {
            using (ExcelPackage excel = new ExcelPackage())
            {
                excel.Workbook.Worksheets.Add("Detalles");
                ExcelWorksheet sheet = excel.Workbook.Worksheets["Detalles"];

                #region HEADER
                int posHeader = 1;
                foreach (string header in headers)
                {
                    sheet.Cells[1, posHeader].Value = header;
                    sheet.Cells[1, posHeader].Style.Font.Bold = true;
                    posHeader++;
                }
                #endregion

                #region ROWS
                int posRow = 2;
                int col = 0;

                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));

                foreach (PropertyDescriptor p in properties)
                {
                    col++;
                    foreach (var item in list.Select(x => p.GetValue(x)).ToList())
                    {
                        sheet.Cells[posRow, col].Value = item;
                        posRow++;
                    }
                    posRow = 2;
                }
                #endregion

                sheet.Cells[sheet.Dimension.Address].AutoFitColumns();

                FileInfo excelFile = new FileInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), $"{fileName}.xlsx"));
                excel.SaveAs(excelFile);
            }
            return true;
        }
        catch (Exception e)
        {
            throw new Exception(e.Message);
        }
    }

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.