将datagrid导出为ex​​cel时出错

时间:2012-04-05 04:22:02

标签: c# asp.net export-to-excel

我正在尝试将数据网格导出为ex​​cel。  使用代码。

 Response.Clear();
                    Response.AddHeader("content-disposition", "attachment;filename=Salary_JV_Posting_For_PG_.xls");
                    Response.Charset = "";
                    Response.ContentType = "application/vnd.xls";
                    System.IO.StringWriter stringWrite = new System.IO.StringWriter();
                    stringWrite.Write("&nbsp;&nbsp;<b><font color=#336699 size = 25px><u>test</u></font></b> ");
                    stringWrite.Write(Environment.NewLine);
                    stringWrite.Write(Environment.NewLine);
                    System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
                    Response.Flush();
                    dgLine.RenderControl(htmlWrite);
                    Response.Write(stringWrite.ToString());
                    Response.End();

我尝试了调试,但是当执行最后一行(response.end)时,出现以下错误

Data = Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.

我正在使用AJAX。

关于Kumar

2 个答案:

答案 0 :(得分:0)

Response.End()绝对会停止页面生命周期执行。

也许你可以尝试HttpContext.Current.ApplicationInstance.CompleteRequest();

而不是它。

答案 1 :(得分:0)

试试这个好友

 Public Sub ExportGridToExcel(ByVal GridView1 As DataGrid, ByVal fileName As String)
        Response.Clear()
        Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xls", fileName))
        Response.Charset = ""
        Response.ContentType = "application/vnd.xls"
        Dim stringWrite As New StringWriter()
        Dim htmlWrite As New HtmlTextWriter(stringWrite)
        GridView1.RenderControl(htmlWrite)
        Response.Write(stringWrite.ToString())
        Response.Flush()
        Response.[End]()
    End Sub

然后在按钮上调用此处

Protected Sub ImageButton1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click
    ExportGridToExcel(DataGrid1, "IT-ADEEL")
End Sub

欢呼声