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

时间:2014-05-27 16:31:05

标签: asp.net vb.net excel export-to-excel

我有一个将ASP Gridview导出为ex​​cel的子程序,它工作正常,但是,当有大量行时我会收到此错误:

Exception of type 'System.OutOfMemoryException' was thrown. 

任何想法如何解决这个问题?这是我导出到excel sub:

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

2 个答案:

答案 0 :(得分:1)

您可以尝试使用StreamWriter将控件直接渲染到输出流,并避免在内存中创建大字符串。
您也可以尝试将Response.Buffer设置为{{1}并且服务器将在处理时直接将输出发送到客户端。

False

答案 1 :(得分:0)

如果this answer在您的情况下无效,那么您应该考虑使用外部库来完成这项工作,因为将大型Excel文件导出为HTML会消耗内存。

查看此示例,了解如何export the datatable of gridview