I have a data table which has 120k rows. I am exporting this data into Excel by below code in ASP.Net using C#. Data was exporting properly when number of records was less than 95K but when it increases it started to give out of memory exception. System.OutOfMemoryException error is coming on below line of code.
public void ExportExcel(DataSet ds)
{
GridView Gv = new GridView();
Gv.DataSource = ds.Tables[0];
Gv.DataBind();
Response.Clear();
Response.Buffer = false;
StringBuilder xlsTop = new StringBuilder();
string xlsFileName = "Report_" + DateTime.Today.ToString();
xlsFileName = "Report_" + DateTime.Now.ToString();
Response.AppendHeader("Content-Disposition", "attachment;filename=" +
xlsFileName + ".xls");
DataTable dt;
dt = ds.Tables[0];
xlsTop.Append("<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" ");
xlsTop.Append("xmlns=\"http://www.w3.org/TR/REC-html40\"><head><meta http-equiv=Content-Type content=\"text/html; charset=windows-1252\">");
xlsTop.Append("<meta name=ProgId content=Excel.Sheet><meta name=Generator content=\"Microsoft Excel 9\"><!--[if gte mso 9]>");
xlsTop.Append("<xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>" + xlsFileName + "</x:Name><x:WorksheetOptions>");
xlsTop.Append("<x:Selected/><x:ProtectContents>False</x:ProtectContents><x:ProtectObjects>False</x:ProtectObjects>");
xlsTop.Append("<x:ProtectScenarios>False</x:ProtectScenarios></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets>");
xlsTop.Append("<x:ProtectStructure>False</x:ProtectStructure><x:ProtectWindows>False</x:ProtectWindows></x:ExcelWorkbook></xml>");
xlsTop.Append("<![endif]-->");
xlsTop.Append("</head><body>");
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
Gv.RenderControl(oHtmlTextWriter);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = false;
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.Write(xlsTop + oStringWriter.ToString() + "</body></html>");// Error is Coming on this Line
HttpContext.Current.ApplicationInstance.CompleteRequest();
Response.End();
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
xlsTop.Clear();
}