Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 将GridView导出到Excel时System.OutOfMemoryException_Asp.net_Vb.net_Excel_Export To Excel - Fatal编程技术网

Asp.net 将GridView导出到Excel时System.OutOfMemoryException

Asp.net 将GridView导出到Excel时System.OutOfMemoryException,asp.net,vb.net,excel,export-to-excel,Asp.net,Vb.net,Excel,Export To Excel,我有一个将ASP Gridview导出到excel的sub,它工作正常,但是,当有大量行时,我收到以下错误: Exception of type 'System.OutOfMemoryException' was thrown. 有什么办法解决这个问题吗?以下是我导出到excel的子项: Protected Sub btnExportMonthlyUK_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn

我有一个将ASP Gridview导出到excel的sub,它工作正常,但是,当有大量行时,我收到以下错误:

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

如果在您的情况下无效,那么您应该考虑外部的库来执行该作业,因为输出大型Excel文件作为HTML是内存消耗。


检查此示例以了解如何操作。

您可以尝试使用
StreamWriter
将控件直接呈现到输出流,并避免在内存中创建大字符串。
您还可以尝试将
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

非常感谢您的回复!这看起来是可行的,除了excel工作表以类似于汉字的方式打开外,有没有办法解决这个问题?@neeko请尝试将所需的编码指定给