asp.net中将GridView数据导出成Excel文件(下)

来源:互联网 发布:js点击获取当前元素 编辑:程序博客网 时间:2024/06/07 07:35

asp.net中将GridView数据导出成Excel文件(下)

///导出GridView中的数据到Excel
privatestatic void GoToExcel(GridViewgvw,stringtitle)
{
stringfileName;
HttpContext.Current.Response.Buffer= true;
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
fileName= string.Format("Export-File{0:yyyy-MM-dd_HH_mm}.xls",DateTime.Now);//生成导出文件名
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+ fileName);//关联要生成的文件
HttpContext.Current.Response.ContentType= "application/vnd.ms-excel";
StringWritertw = new System.IO.StringWriter();//创建StringWriter对象实例
HtmlTextWriterhw = new System.Web.UI.HtmlTextWriter(tw);

//根据StringWriter对象创建HtmlTextWriter对象实例
gvw.RenderControl(hw);//将GridView内输入HtmlTextWriter中,并跟踪信息
if(!string.IsNullOrEmpty(title))//如果title 不为空则加入title内容
{
HttpContext.Current.Response.Write("<b><center><fontsize=3 face=Verdana color=#0000FF>" +title+"</font></center></b>");}
HttpContext.Current.Response.Write(tw.ToString());//正真写入内容到文件
 
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
HttpContext.Current.Response.End();
gvw.Dispose();//释放过程中的对象实例
tw.Dispose();
hw.Dispose();
gvw= null;
tw= null;
hw= null;
}

}
}

调用示例:
Listorders=this.GetOrders
();// 得到ist数据
ToExcel
.ExportToExcel(orders,
newstring[] {"OrderNo","CustomerNo","UserNo","ModelNo","Quantity","Price","Amount","OrderDate"},
newstring[] {"订单","客户代码","用户代码","型号","数量","价格","金额","订货日期"}
);

http://blog.sina.com.cn/s/blog_4d174ff90100i4dd.html

原创粉丝点击