[英]Visual Studio exception of type 'system.outofmemoryexception'
[英]ASP System.OutOfMemoryException only caught in Visual Studio not on production server
我编写了一种使用格式将asp GridView对象的内容导出到Excel的方法。 在非常罕见但完全可重复的情况下,该特定GridView具有大量行(24k),该方法将失败并被相应地捕获和处理。
这在Visual Studio(2015)中完美运行,但在移至生产服务器时则无效,后者转而抛出System.OutOfMemoryException。
方法:
protected void ExportToExcel(object sender, EventArgs e)
{
Button clickedButton = (Button)sender;
GridView selectedGridview = GridView1;
string filename = "FileNameHere";
// Hidden unimportant selection of gridview
if (selectedGridview.Rows.Count > 0)
{
try
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
selectedGridview.AllowPaging = false;
foreach (TableCell cell in selectedGridview.HeaderRow.Cells)
{
cell.BackColor = selectedGridview.HeaderStyle.BackColor;
}
foreach (GridViewRow row in selectedGridview.Rows)
{
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = selectedGridview.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = selectedGridview.RowStyle.BackColor;
}
cell.CssClass = "textmode";
cell.Attributes.Add("style", "mso-number-format:\\@");
}
}
selectedGridview.RenderControl(hw);
//style to format numbers to string
string style = @"<style> .textmode {mso-number-format:\\@;} </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
}
}
catch(System.OutOfMemoryException OOMex)
{
Response.Clear();
// Another method gets called here to instead create a CSV file (much lighter on memory)
}
finally
{
Response.Flush();
Response.End();
}
}
关于为什么它在本地工作但在生产中引发异常的任何想法?
任何帮助将不胜感激。
更新:
从那以后,我移到了Mike Gledhill的库中,该库大大降低了复杂性,但仍然会引发相同的错误。
与他讨论解决方案后,我已经设置了<httpRuntime maxRequestLength="1000000000" executionTimeout="7200"/>
,并通过忽略会话变量并将DataTable直接导出到Excel进行了测试。 这是相同的,唯一的区别是现在在大型结果集上,我得到System.IO.IsolatedStorage.IsolatedStorageException: Unable to create the store directory
。 我目前正在咨询服务器管理员以纠正此问题。
更新2:
我按照以下说明解决了System.IO.IsolatedStorage.IsolatedStorageException
: MSDN论坛
现在一切都正常工作了100%!
底线:
我仍然想知道异常如何或为什么会超出我的尝试/捕获范围。 如果服务器的可寻址/可分配内存不足,是否有可能不会运行catch子句? 也许它在catch子句中的内存“用完了”并且无法重新捕获?
我无法确切告诉您为什么会发生该异常,但是如果您要编写特别大的Excel文件,我建议您使用OpenXML
和OpenXmlWriter
库正确执行。
这是一个免费的C#库(带有源代码),它将使用DataSet
, DataTable
或List<>
并创建一个真实的Excel .xlsx文件。
只需将用于填充GridView
任何数据源传递给它即可,例如:
CreateExcelFile.CreateExcelDocument(myDataSet, "YourFilename.xlsx");
而且,如果您尝试在网站上创建Excel文件,则只需将HttpResponse
传递给它即可:
CreateExcelFile.CreateExcelDocument(myDataSet, "YourFilename.xlsx", Response);
但是,是的,您将需要修改此代码以添加Excel格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.