List<T>集合导出csv方法参考,通过增加自定义的属性控制输出的字段。

public string CreateAdvExcel(List<GridScoreManager> lt)
        {
            StringBuilder builder = new StringBuilder();
            if (lt == null || (0 == lt.Count))
            {
                return "";
            }
            System.Reflection.PropertyInfo[] myPropertyInfo = lt.First().GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
            int i = 0, j;
            for (i = 0, j = myPropertyInfo.Length; i < j; i++)
            {
                System.Reflection.PropertyInfo pi = myPropertyInfo[i];
                var ex = pi.GetCustomAttribute<ExAttribute>();
                if (ex != null)
                {
                    string headname = ex.HeaderName;//单元格头部
                    builder.Append(string.Format(""{0}"", headname.Replace(""", """")));
                    builder.Append(",");
                }               
            }
            builder.AppendLine();
            foreach (GridScoreManager t in lt)
            {
                if (lt == null)
                {
                    continue;
                }
                for (i = 0, j = myPropertyInfo.Length; i < j; i++)
                {
                    System.Reflection.PropertyInfo pi = myPropertyInfo[i];
                    var ex = pi.GetCustomAttribute<ExAttribute>();
                    if (ex != null)
                    {
                        string str = string.Format(""{0}"", pi.GetValue(t, null).ToString().Replace(""", """"));
                        builder.Append(str).Append(",");
                    }                        
                    
                }
                builder.AppendLine();
            }


            return builder.ToString();

        }
    }
    public class GridScoreManager
    {

        [ExAttribute(HeaderName = "aaaa  aa Manager Nameaaaa  , "aa Manager Nameaaaa  aa Manager Nameaaaa  aa Manager Nameaaaa  aa Manager Name")]
        public string Name { get; set; }
        [ExAttribute(HeaderName ="Identity")]
        public int Id { get; set; }

        public int Age { get; set; }

    }

    public class ExAttribute : Attribute
    {
        public string HeaderName { get; set; }
    }

  

原文地址:https://www.cnblogs.com/sgciviolence/p/5631425.html