反射导出 Excel

/// <summary>
    /// List 数据导出Excel
    /// </summary>
    /// <param name="list">数据</param>
    /// <param name="filename">文件名称</param>
    /// <param name="ColumNames">标题名(数组-所有标题)</param>
    /// <param name="FileNames">标题名对应的数据库字段名称(数组-标题对应字段)</param>
    public void HtmlToExcel<T>(IList<T> list, string filename, string[] ColumNames, string[] FileNames)
    {
        // 通过反射获取该类 下面所有公共属性值
        PropertyInfo[] propertyInfos = list.First().GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
        int i, j, s = 0;
        //拼接HTML Table数据结构
        string xls = @"<Table border='1'><tr>";      
        //添加Excel中第一行的标题
        for (i = 0; i < ColumNames.Length; i++)
        {
            xls += @"<td>" + ColumNames[i] + @"</td>";
        }
        xls = xls + @"</tr>";
        //添加Excel数据
        foreach (T item in list)
        {
            xls += @"<tr>";
            if (list == null)
            {
                continue;
            }
            for (int m = 0; m < FileNames.Length; m++)
            {
                for (s = 0; s < propertyInfos.Length; s++)
                {
                    PropertyInfo pi = propertyInfos[s];
                    // 判断反射得到的属性 和 传入进来的 FileNames 中的值是否相同
                    //如何相同就得到它的值
                    if (pi.Name == FileNames[m])
                    {
                        string value = string.Format("{0}", pi.GetValue(item, null));
                        DateTime date;
                        //判断是否日期 转换短日期
                        if (DateTime.TryParse(value, out date))
                        {
                            xls += @"<td>" + date.ToShortDateString() + "&nbsp;</td>";
                            continue;
                        }
                        xls += @"<td>" + value + "&nbsp;</td>";
                    }
                }
            }
            xls += @"</tr>";
        }
        xls = xls + @"</Table>";

        //清空输出缓存、设置编码、输出类型
        HttpContext.Current.Response.Clear();
        // 指定返回的是一个不能被客户端读取的流,必须被下载
        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        HttpContext.Current.Response.Charset = "UTF-8";
        HttpContext.Current.Response.Buffer = true;
        HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("GB2312");
        HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xls", filename));
        HttpContext.Current.Response.Write(xls);
        HttpContext.Current.Response.End();
    }
    #endregion

 

posted @ 2018-05-31 18:11  打不死的小强5  阅读(256)  评论(0编辑  收藏  举报