2

I have a sub that exports a ASP Gridview to excel, it works fine, however, when there are a large amount of rows I get this error:

Exception of type 'System.OutOfMemoryException' was thrown. 

Any ideas how to solve this? Here is my export to 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 Answers 2

1

You can try rendering the control directly to the output stream by using a StreamWriter and avoid creating a large string in memory.
You can also try setting Response.Buffer to False and the server will send the output to the client directly as it is processed.

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
Sign up to request clarification or add additional context in comments.

2 Comments

thank you so much for your reply! this looks like it works, except the excel sheet opens in what looks like chinese characters, any way to fix this?
@neeko Try specifying the desired encoding to the StreamWriter constructor
0

If this answer is not valid in your case, then you should consider an external library to do the job, because exporting large Excel files as HTML is memory consuming.

Check this sample about how to export the datatable of gridview.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.