将GridView导出到Excel时出现System.OutOfMemoryException

我有一个子导出一个ASP Gridview的Excel,它工作正常,但是,当有大量的行我得到这个错误:

Exception of type 'System.OutOfMemoryException' was thrown. 

任何想法如何解决这个问题? 这是我出口到Excel的子:

 Protected Sub btnExportMonthlyUK_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportMonth.Click Dim title As String title = "MonthlyReportUK" Response.Clear() Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xls", title)) Response.Charset = "" Response.ContentType = "application/vnd.xls" Response.ContentEncoding = Encoding.Unicode Response.BinaryWrite(Encoding.Unicode.GetPreamble()) Dim strWr As New StringWriter() Dim HtmlWr As New HtmlTextWriter(strWr) monthlyReportsIE.AllowPaging = False monthlyReportsIE.DataBind() monthlyReportsIE.RenderControl(HtmlWr) Response.Write(strWr.ToString()) Response.End() End Sub 

您可以尝试使用StreamWriter将控件直接渲染到输出stream,并避免在内存中创build大string。
您也可以尝试将Response.Buffer设置为False并在服务器处理完毕后直接将输出发送到客户端。

 Protected Sub btnExportMonthlyUK_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportMonth.Click Dim title As String title = "MonthlyReportUK" Response.Clear() Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xls", title)) Response.Charset = "" Response.ContentType = "application/vnd.xls" Response.ContentEncoding = Encoding.Unicode Response.BinaryWrite(Encoding.Unicode.GetPreamble()) Response.Buffer = False monthlyReportsIE.AllowPaging = False monthlyReportsIE.DataBind() Using strWr As new StreamWriter(response.OutputStream) Using htmlWr As new HtmlTextWriter(strWr) monthlyReportsIE.RenderControl(htmlWr) End Using End Using Response.End() End Sub 

如果这个答案在你的情况下是无效的,那么你应该考虑一个外部库来完成这个工作,因为以HTML格式导出大的Excel文件是耗费内存的。

检查这个示例关于如何导出gridview的数据表 。