Blog de Francisco Velázquez

otro blog personal

Exportar a csv desde c#

leave a comment »

Una pequeña utilidad para exportar listas genéricas a csv, usando expresiones lambda.

public class ExportExcel<T> where T : class
    {
        private StringBuilder sb;        

        public ExportExcel()
        {            
            sb = new StringBuilder();
            if (HttpContext.Current != null)
                Context = HttpContext.Current;
        }

        public string Filename { get; set; }
        public HttpContext Context { get; set; }

        public void Export(List<T> l, Expression<Func<T, object>> expression)
        {
            if (string.IsNullOrEmpty(Filename))
                return;

            build(l, expression);

            Context.Response.AddHeader("content-disposition", "attachment;filename=" + Filename);
            Context.Response.Charset = string.Empty;
            Context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Context.Response.ContentType = "application/CSV";            
            Context.Response.Write(sb.ToString());
            Context.Response.End();
        }

        public string ToString(List<T> l, Expression<Func<T, object>> expression)
        {            
            build(l, expression);
            return sb.ToString();
        }

        private void build(List<T> l, Expression<Func<T, object>> expression)
        {
            sb = new StringBuilder();
            List<string> propertiesName = new List<string>();
            NewArrayExpression array = expression.Body as NewArrayExpression;
            foreach (object obj in (IEnumerable<object>)(array.Expressions))
            {
                string propertyName = obj.ToString().Remove(0, obj.ToString().IndexOf(".") + 1);
                propertyName = propertyName.Replace(")", "");
                sb.Append(propertyName + ";");
                propertiesName.Add(propertyName);
            }
            sb.AppendLine();

            foreach (var i in l)
            {
                foreach (var propertyName in propertiesName)
                {
                    sb.Append(getPropertyValue(i, propertyName).ToString() + ";");
                }
                sb.AppendLine();
            }
        }

        internal static object getPropertyValue(object obj, string propertyName)
        {
            const System.Reflection.BindingFlags bindingFlags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance;

            var pi = typeof(T).GetProperties(bindingFlags).Where(prop => prop.Name == propertyName).SingleOrDefault();
            return pi.GetValue(obj, null);
        }
    }

Written by fravelgue

September 27, 2012 at 7:36 pm

Posted in .net

Tagged with , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: