现在的位置: 首页 > 综合 > 正文

C#导出泛型IList到Excel

2018年04月18日 ⁄ 综合 ⁄ 共 2203字 ⁄ 字号 评论关闭
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace WebApp.Test
{
    /// <summary>
    /// List<T>导出类
    /// </summary>
    /// <typeparam name="T">列表中的元素类型</typeparam>
    public class ExcelHelperForIList<T>
    {
        /// <summary>
        /// 泛型导出Excel
        /// </summary>
        /// <param name="lt">要导出的List集合</param>
        /// <param name="fileName">文件名</param>
        /// <param name="fieldNames">导出的字段名()</param>
        /// <param name="showNames">Excel标题行(需与FieldNames对应)</param>
        /// <returns></returns>
        public static string CreateAdvExcel(IList<T> lt, string fileName, string[] fieldNames, string[] showNames)
        {
            StringBuilder builder = new StringBuilder();
            Random rn = new Random();
            string name = fileName;
            //通过反射得到对象的属性集合  
            System.Reflection.PropertyInfo[] myPropertyInfo = lt.First().GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
            int i = 0, j;
            for (int m = 0; m < fieldNames.Length; m++)
            {
                //遍历属性集合生成excel的表头标题  
                for (i = 0, j = myPropertyInfo.Length; i < j; i++)
                {
                    System.Reflection.PropertyInfo pi = myPropertyInfo[i];
                    string headname = pi.Name;//单元格头部
                    if (headname == fieldNames[m])
                    {
                        builder.Append(showNames[m]);
                        builder.Append("\t");
                    }
                }
            }
            builder.Append("\n");
            //遍历集合生成excel的行集数据
            foreach (T item in lt)
            {
                if (lt == null)
                {
                    continue;
                }
                for (int m = 0; m < fieldNames.Length; m++)
                {
                    for (i = 0, j = myPropertyInfo.Length; i < j; i++)
                    {
                        PropertyInfo pi = myPropertyInfo[i];
                        if (pi.Name == fieldNames[m])
                        {
                            string str = string.Format("{0}", pi.GetValue(item, null)).Replace("\n", "");
                            str = str.Replace(" ", " ");
                            if (str == "")
                            {
                                builder.Append("\t");
                            }
                            else
                            {
                                builder.Append(str + "\t");//横向跳到另一个单元格
                            }
                        }
                    }
                }

                builder.Append("\n");//换行
            }
            StringWriter sw = new StringWriter();
            sw.WriteLine(builder);
            sw.Close();

            HttpContext.Current.Response.Clear();
            // 指定返回的是一个不能被客户端读取的流,必须被下载
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.Charset = "UTF-8";
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xls", name));
            HttpContext.Current.Response.Write(builder);
            HttpContext.Current.Response.End();
            return builder.ToString();
        }
    }
}

在网上找了一些方法但是最终整理成这个类,代码可能有冗余,尚在研究当中,同时也希望同志们指点一二。

抱歉!评论已关闭.