发布于 2016-06-01 13:44:49 | 87 次阅读 | 评论: 1 | 来源: 网友投递
ASP.NET
ASP.NET 是.NET FrameWork的一部分,是一项微软公司的技术,是一种使嵌入网页中的脚本可由因特网服务器执行的服务器端脚本技术,它可以在通过HTTP请求文档时再在Web服务器上动态创建它们。 指 Active Server Pages(动态服务器页面) ,运行于 IIS(Internet Information Server 服务,是Windows开发的Web服务器)之中的程序 。
/// <summary>
/// 将一组对象导出成EXCEL
/// </summary>
/// <typeparam name="T">要导出对象的类型</typeparam>
/// <param name="objList">一组对象</param>
/// <param name="FileName">导出后的文件名</param>
/// <param name="columnInfo">列名信息</param>
public static void ExExcel<T>(List<T> objList, string FileName, Dictionary<string, string> columnInfo)
{
if (columnInfo.Count == 0) { return; }
if (objList.Count == 0) { return; }
//生成EXCEL的HTML
string excelStr = "";
Type myType = objList[0].GetType();
//根据反射从传递进来的属性名信息得到要显示的属性
List<PropertyInfo> myPro = new List<PropertyInfo>();
foreach (string cName in columnInfo.Keys)
{
PropertyInfo p = myType.GetProperty(cName);
if (p != null)
{
myPro.Add(p);
excelStr += columnInfo[cName] + "\t";
}
}
//如果没有找到可用的属性则结束
if (myPro.Count == 0) { return; }
excelStr += "\n";
foreach (T obj in objList)
{
foreach (PropertyInfo p in myPro)
{
excelStr += p.GetValue(obj, null) + "\t";
}
excelStr += "\n";
}
//输出EXCEL
HttpResponse rs = System.Web.HttpContext.Current.Response;
rs.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
rs.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
rs.ContentType = "application/ms-excel";
rs.Write(excelStr);
rs.End();
}
/// <summary>
/// 将一组对象导出成EXCEL
/// </summary>
/// <typeparam name="T">要导出对象的类型</typeparam>
/// <param name="objList">一组对象</param>
/// <param name="FileName">导出后的文件名</param>
/// <param name="columnInfo">列名信息</param>
public static void ExExcel<T>(List<T> objList, string FileName, Dictionary<string, string> columnInfo)
{
if (columnInfo.Count == 0) { return; }
if (objList.Count == 0) { return; }
//生成EXCEL的HTML
StringBuilder excelStr = new StringBuilder(objList.Count * columnInfo.Count);
Type myType = objList[0].GetType();
//根据反射从传递进来的属性名信息得到要显示的属性
List<PropertyInfo> myPro = new List<PropertyInfo>();
foreach (string cName in columnInfo.Keys)
{
PropertyInfo p = myType.GetProperty(cName);
if (p != null)
{
myPro.Add(p);
excelStr.Append(columnInfo[cName]).Append("\t");
}
}
//如果没有找到可用的属性则结束
if (myPro.Count == 0) { return; }
excelStr.Append("\n");
foreach (T obj in objList)
{
foreach (PropertyInfo p in myPro)
{
excelStr.Append(p.GetValue(obj, null)).Append("\t");
}
excelStr.Append("\n");
}
//输出EXCEL
HttpResponse rs = System.Web.HttpContext.Current.Response;
rs.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
rs.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
rs.ContentType = "application/ms-excel";
rs.Write(excelStr);
rs.End();
}
}