![](/img/trans.png)
[英]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.