之前项目中需要一个导出数据到Excel的功能,现在将代码记录下来。其实将girdView中的数据导出的代码很简单,如下:
) { Response.Charset="GB2312"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); Response.AppendHeader("Content-Disposition", "attachment; filename=" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".xls"); Response.ContentType = "application/vnd.ms-excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); GvList.RenderControl(htw); Response.Write(sw.ToString()); Response.Flush(); Response.End(); } else { Response.Write("<script>alert('无日志数据!');</script>"); }
后台代码
以上导出的数据为girdView的一页的数据,如果想将所有的数据导出,就得取消girdView的分页,AllowPaging设置为false,并重新绑定girdView,导出后在恢复原样。