GridView输入Excel时出现"System.OutOfMemoryException: Out of memory"及其解决方案。
一般我们用GridView输出Excel是,代码都是这样写的:
Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename="+filename+".xls"); Response.Charset = ""; this.EnableViewState=false; 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); DataGrid myDataGrid=new DataGrid(); myDataGrid.DataSource=dsReport.Tables[1]; myDataGrid.DataBind(); myDataGrid.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End();
当gridview的数据比较大的时候,会出现 System.OutOfMemoryException: Out of memory的错误。
解决的方法当然是减少内存的空间的占用量。
一下是从网上搜来的解决方案:
Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename="+filename+".xls"); Response.Charset = ""; this.EnableViewState=false; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/vnd.xls"; System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(Response.Output); DataGrid myDataGrid=new DataGrid(); myDataGrid.DataSource=dsReport.Tables[1]; myDataGrid.DataBind(); myDataGrid.RenderControl(htmlWrite); Response.End(); /* This should divide the memory required by the actual report output HTML by 3, because before you were storing the entire thing in memory a total of at least three times before: - In the StringBuilder - In the String from the StringBuilder.ToString() - In the Response object */