Popular

Obten claves web y navega gratis Router keygen para Android

Error 403 Forbidden con phpmyadmin y WAMP Server

Realizar suma, resta y división con javascript

Exportar a Excel DataGrid con WPF

Un tema interesante el que ahora planteamos es el exportar datos de nuestra aplicación a Excel, para las personas que nos ha tocado trabajar con empresas que están muy acostumbradas a usar sus procesos de sistemas en hojas de excel, esto es muy importante ya que ellos requieren seguirlo haciéndolo para no cambiar tanto el proceso a sus empleados, o al menos de una manera tan rápida. 

Por lo que ahora veremos como exportar un DataGrid a excel, aquí les dejo la imagen del ejemplo sencillo que he realizado y como culminará al final de realizarlo:


Bueno ahora como realizamos esto primero que nada construiremos una clase Articles que contendrá como atributos { Cve, Nombre, Cantidad}. Es un ejemplo muy sencillo así que quedaría de la siguiente manera: 

namespace exporttoexcel
{
    class Articles
    {
        private int _Cve;

        public int Cve
        {
            get { return _Cve; }
            set { _Cve = value; }
        }

        private string _Name;

        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }

        private int _Cantidad;

        public int Cantidad
        {
            get { return _Cantidad; }
            set { _Cantidad = value; }
        }
    }
}



Ahora crearemos la clase que nos permitirá exportar a excel. 

using System.Reflection;

using Excel = Microsoft.Office.Interop.Excel;
using System.Windows.Input;
using System.Windows;

namespace exporttoexcel
{
    public class ExportingExcell<T, U>
        where T : class
        where U : List<T>
    {
        public List<T> dataToPrint;
        //Excel object reference.
        private Excel.Application excelApp = null;
        private Excel.Workbooks books = null;
        private Excel._Workbook book = null;
        private Excel.Sheets sheets = null;
        private Excel._Worksheet sheet = null;
        private Excel.Range range = null;
        private Excel.Font font = null;
        // Optional argument variable
        private object optionalValue = Missing.Value;

        public void GenerateReport()
        {
            try
            {
                if (dataToPrint != null)
                {
                    if (dataToPrint.Count != 0)
                    {
                        Mouse.SetCursor(Cursors.Wait);
                        CreateExcelRef();
                        FillSheet();
                        OpenReport();
                        Mouse.SetCursor(Cursors.Arrow);
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Error while generating Excel report", e.Message);
            }
            finally
            {
                ReleaseObject(sheet);
                ReleaseObject(sheets);
                ReleaseObject(book);
                ReleaseObject(books);
                ReleaseObject(excelApp);
            }
        }

        private void OpenReport()
        {
            //MessageBoxControl.Show("The Excel File Has Been Created, Press Acept To See It", "", MessageBoxControlImage.Information, MessageBoxButton.OK);
            excelApp.Visible = true;
        }

        private void FillSheet()
        {
            object[] header = CreateHeader();
            WriteData(header);
        }

        private void WriteData(object[] header)
        {
            object[,] objData = new object[dataToPrint.Count, header.Length];

            for (int j = 0; j < dataToPrint.Count; j++)
            {
                var item = dataToPrint[j];
                for (int i = 0; i < header.Length; i++)
                {
                    var y = typeof(T).InvokeMember
                    (header[i].ToString(), BindingFlags.GetProperty, null, item, null);
                    objData[j, i] = (y == null) ? "" : y.ToString();
                }
            }

            AddExcelRows("A2", dataToPrint.Count, header.Length, objData);
            AutoFitColumns("A1", dataToPrint.Count + 1, header.Length);
        }

        private void AutoFitColumns(string startRange, int rowCount, int colCount)
        {
            range = sheet.get_Range(startRange, optionalValue);
            range = range.get_Resize(rowCount, colCount);
            range.Columns.AutoFit();
        }

        //this method is the one im gonna make for alll the aplication
        private object[] CreateHeader()
        {
            PropertyInfo[] headerInfo = typeof(T).GetProperties();

            List<object> objHeaders = new List<object>();
            for (int n = 0; n < headerInfo.Length; n++)
            {
                if (headerInfo[n].Name.ToString() != "ExtensionData")
                    objHeaders.Add(headerInfo[n].Name);
            }

            var headerToAdd = objHeaders.ToArray();
            AddExcelRows("A1", 1, headerToAdd.Length, headerToAdd);
            SetHeaderStyle();

            return headerToAdd;
        }

        private void SetHeaderStyle()
        {
            font = range.Font;
            font.Bold = true;
        }

        private void AddExcelRows(string startRange, int rowCount, int colCount, object values)
        {
            range = sheet.get_Range(startRange, optionalValue);
            range = range.get_Resize(rowCount, colCount);
            range.set_Value(optionalValue, values);
        }

        private void CreateExcelRef()
        {
            excelApp = new Excel.Application();
            books = (Excel.Workbooks)excelApp.Workbooks;
            book = (Excel._Workbook)(books.Add(optionalValue));
            sheets = (Excel.Sheets)book.Worksheets;
            sheet = (Excel._Worksheet)(sheets.get_Item(1));
        }

        private void ReleaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show(ex.Message.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }
    }
}


Finalmente así llenaremos nuestro grid y exportaremos: 
public partial class MainWindow : Window
    {
        //Lista de objetos Articles;
        List<Articles> ListArticles = null;
        public MainWindow()
        {
            InitializeComponent();

            //Llenaremos nuestra lista ya que no tenemos conexion a base de datos
            this.ListArticles = new List<Articles>();
            FillArticles();
        }

        private void FillArticles()
        {
            this.ListArticles.Add(new Articles { Cve = 1, 
                       Name = "Boligrafo Negro", Cantidad = 125 });
            this.ListArticles.Add(new Articles { Cve = 2,
                       Name = "Lapiz 2.5", Cantidad = 210 });
            this.ListArticles.Add(new Articles { Cve = 3, 
                       Name = "Cuaderno Profesional", Cantidad = 289 });
            this.ListArticles.Add(new Articles { Cve = 4, 
                       Name = "Goma para borrar", Cantidad = 110 });
            this.ListArticles.Add(new Articles { Cve = 5, 
                       Name = "Corrector lápiz", Cantidad = 30 });
            this.ListArticles.Add(new Articles { Cve = 6, 
                       Name = "Agenda telefonica", Cantidad = 20 });
            this.ListArticles.Add(new Articles { Cve = 7, 
                       Name = "Lápices de colores", Cantidad = 83 });
            this.ListArticles.Add(new Articles { Cve = 8, 
                       Name = "Hojas para folder", Cantidad = 20 });
            this.ListArticles.Add(new Articles { Cve = 9, 
                       Name = "Cinta adhesiva", Cantidad = 33 });
            this.ListArticles.Add(new Articles { Cve = 10, 
                       Name = "Engrapadora", Cantidad = 230 });
            this.ListArticles.Add(new Articles { Cve = 11, 
                       Name = "Tijeras", Cantidad = 55 });

            //Agregar Lista al Datagrid de WPF
            this.dtgArticles.ItemsSource = null;
            this.dtgArticles.ItemsSource = this.ListArticles;
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            exporttoexcel.ExportingExcell<Articles, List<Articles>> s = 
                                 new ExportingExcell<Articles, List<Articles>>();
            s.dataToPrint = this.dtgArticles.ItemsSource as List<Articles>;
            s.GenerateReport();
        }
    }


Descargar Ejemplo

Comentarios

Entradas populares de este blog

Error 403 Forbidden con phpmyadmin y WAMP Server

Número de filas afectadas por instrucción PL/SQL en Oracle [Utilidades].

Como truncar un número decimal en C# sin redondear.