从.NET代码中导出Excel数据时,引发了“System.OutOfMemoryException”

我有一个代码来debugging我试图导出Excel中的数据。 它适用于较小的数据,但是当数据大小增加到几千时,我得到“内存exception”。 我的应用程序正在IIS 6.0上运行。 任何build议?

PS:当进程占用超过1.2 GB的内存时,进程通常会失败(查看任务pipe理器)

Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter) If (IsExportToCSV) Then Response.Clear() Response.ContentType = "application/vnd.ms-excel" Response.ContentType = "a" 'Remove the charset from the Content-Type header. Response.Charset = "" 'Turn off the view state. Page.EnableViewState = False Dim tw As System.IO.StringWriter tw = New System.IO.StringWriter Dim hw As HtmlTextWriter = New HtmlTextWriter(tw) 'Get the HTML for the control. Me.GridView1.AllowPaging = False Me.GridView1.DataBind() Me.GridView1.EnableViewState = False Me.GridView1.AutoGenerateEditButton = False Me.GridView1.RenderControl(hw) Response.Write(tw.ToString) Response.Flush() Response.End() Else MyBase.Render(writer) End If End Sub 

完美解决scheme

我一直在争取一段时间,解决scheme是这么简单:不要build立一个string传递响应写string存在内存中,而是把每一行直接进入响应使用多个Response.Write调用

DataTable的示例转换为HTML表格并发送到客户端作为Excel …

 string contentType = "Reports.xls"; string fileName = "application/msexcel"; Response.Clear(); Response.Buffer = true; Response.ContentType = contentType; string attachment = string.Format("attachment; filename=\"{0}\"", fileName); Response.AddHeader("Content-Disposition: ", attachment); byte[] preamble = Encoding.UTF8.GetPreamble(); Response.BinaryWrite(preamble); string strFontSize = "12"; Response.Write("<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" \r\n xmlns:x=\"urn:schemas-microsoft-com:office:excel\" \r\n xmlns=\"http://www.w3.org/TR/REC-html40\">"); Response.Write(@"<head>"); Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=windows-1252\">"); Response.Write("<meta name=ProgId content=Excel.Sheet>"); Response.Write("<meta name=Generator content=\"Microsoft Excel 11\">"); Response.Write(@"</head>"); Response.Write(@"<body>"); Response.Write(@"<table style='width: 100%; font-size:" + strFontSize + ";' border='1'>"); foreach (DataColumn column in dt.Columns) { Response.Write(@"<td><b>" + column.ColumnName + "</b></td>"); } Response.Write(@"</tr>"); int intCell = 0; string strCell = ""; foreach (DataRow row in dt.Rows) { intCell = 0; Response.Write(@"<tr>"); foreach (DataColumn column in dt.Columns) { strCell = row.ItemArray[dt.Columns[column.ColumnName].Ordinal].ToString().Trim(); Response.Write(@"<td>" + strCell + "</td>"); } Response.Write(@"</tr>"); } Response.Write(@"</table>"); Response.Write(@"</body>"); Response.Write(@"</html>"); Response.End(); 

直接写每一行信息的响应stream,而不是传递槽StringWriter