在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
这是asp.net 中将页面数据导出word、excel的常用代码(以datagrid为例) 导出word代码: Response.Clear(); Response.Charset = "utf-8"; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/vnd.word"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); DataGrid1.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); 导出excel代码: Response.Clear(); Response.Charset = "utf-8"; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/vnd.xls"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); DataGrid1.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); 这个代码很容易可以在网上搜到,但是如果页面的datagrid有排序和分页时就会出现错误,这是时候如果用循环导出数据,实在是不爽。现有一个新的办法: 第一种: 复制同样一个datagrid,赋同样的数据,隐藏,取消分页和排序功能: Datagrid2.Visible=true; Response.Charset = "utf-8"; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/vnd.xls"; System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); Datagrid2.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); 即可倒出漂亮的excel文件,word同上 同理可得:导出前取消分页和排序,导出再恢复,可以实现这个功能 |
请发表评论