我有一个代码来调试我尝试在Excel中导出数据的位置。它适用于较小的数据但是当数据大小增加到几千时,我会得到“Out of Memory exception”。我的应用程序在IIS 6.0上运行。有什么建议?
PS:当内存超过1.2 GB(查看任务管理器)时,该过程通常会失败
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
答案 0 :(得分:4)
完美解决方案!
我一直在争论这个问题,解决方案很简单:不要构建一个字符串来传递给响应写入,因为字符串存在于内存中,而是使用多个Response将每一行直接放入响应中。写电话
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();
答案 1 :(得分:1)
直接写每行直接信息响应流而不是通过StringWriter