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

本文介绍了一种使用C#编程语言动态生成Excel文件的方法。通过反射获取对象属性,并利用这些属性创建带有特定头部信息的Excel表格。该方法适用于需要导出数据到Excel的应用场景。
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值