0

我有一个代码来调试我试图在 Excel 中导出数据的位置。它适用于较小的数据,但是当数据大小增加到数千时,我得到“内存不足异常”。我的应用程序在 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
4

2 回答 2

4

完美解决方案!

我一直在与这个作斗争,解决方案非常简单:不要构建一个字符串来传递给响应写入,因为字符串存在于内存中,而是使用多个 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();
于 2012-10-31T19:22:27.183 回答
1

将每一行直接写入响应流的信息,而不是通过 StringWriter

于 2012-08-28T14:29:47.943 回答