Gridview到Excel不会在Excel中产生任何结果

时间:2013-06-25 19:44:53

标签: c# excel gridview

我希望有人能让我走上正轨。我需要将Gridview下载到Excel:

Gridview出现在我的.ascx页面上没有问题...我按下按钮,以下代码被执行,我得到保存或打开的提示,但后来我得到" file.xls&# 34;格式不正确或已损坏,我按OPEN ...我的Excel中没有任何内容。我记得以前必须这样做,我遇到了麻烦......我错过了什么:

protected void dwnLoad(object sender, EventArgs e)
        {
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment; filename=kbNotification.xls");
            Response.Charset = "";
            //Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/vnd.xls";
            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWrite);
            GridView1.RenderControl(htmlWriter);
            Response.End();
        }

1 个答案:

答案 0 :(得分:0)

由于我的Gridview位于.ascx页面中... default.aspx页面必须包含两部分:在后面的代码中:

public override void VerifyRenderingInServerForm(Control control)
        {
            return;
        }

并在顶部<%@ page中的default.aspx中 - EnableEventValidation =“false”

这对于处理需要在标签之间的gridview是必要的。

另外,由于某些愚蠢的原因,我的.ascx页面上有标签......需要将其取出。

然后,最终使用以下代码的OnClick事件:

protected void dwnLoad(object sender, EventArgs e)
        {
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment; filename=kbNotification.xls");
            Response.Charset = "";
            //Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/vnd.xls";
            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWrite);
            GridView1.RenderControl(htmlWriter);
            Response.Write(stringWrite.ToString());
            Response.End();
        }

我错过了Response.Write ...哎呀!

现在我的Excel正在显示我的屏幕内容。 我希望这可以帮助其他可能遇到同样问题的人。