List集合 导出 Excel

本文将介绍如何使用C#编程语言结合System.Reflection库创建一个自定义的Excel文件,包括生成文件名、设置文件路径、获取属性信息并填充数据。
public string CreateAdvExcel(IList<DocAdvInfo> lt)
        {
            StringBuilder builder = new StringBuilder();
            Random rn = new Random();
            string name = rn.Next(9999) + ".xls";
            string path = Server.MapPath("\\Document\\" + name);
            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];
                string headname = pi.Name;//单元格头部
                builder.Append(headname);
                builder.Append("\t");
            }
            builder.Append("\n");
            foreach (DocAdvInfo t in lt)
            {
                if (lt == null)
                {
                    continue;
                }
                for (i = 0, j = myPropertyInfo.Length; i < j; i++)
                {
                    System.Reflection.PropertyInfo pi = myPropertyInfo[i];
                    string str = string.Format("{0}", pi.GetValue(t, null)).Replace("\n", "");
                    if (str == "")
                    {
                        builder.Append("\t");
                    }
                    else
                    {
                        builder.Append(str + "\t");//横向跳到另一个单元格
                    }
                }
                builder.Append("\n");//换行
            }
            StreamWriter sw = new StreamWriter(path, false, System.Text.Encoding.GetEncoding("GB2312"));
            sw.Write(builder.ToString());//输出
            sw.Flush();
            sw.Close();

 

 

转载于:https://www.cnblogs.com/huhaihua/p/3745371.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值