我有一个将ASP Gridview导出为excel的子程序,它工作正常,但是,当有大量行时我会收到此错误:
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
答案 0 :(得分:1)
您可以尝试使用StreamWriter
将控件直接渲染到输出流,并避免在内存中创建大字符串。
您也可以尝试将Response.Buffer
设置为{{1}并且服务器将在处理时直接将输出发送到客户端。
False
答案 1 :(得分:0)
如果this answer在您的情况下无效,那么您应该考虑使用外部库来完成这项工作,因为将大型Excel文件导出为HTML会消耗内存。
查看此示例,了解如何export the datatable of gridview。