【问题标题】:Gridview to Excel not yielding any results in ExcelGridview 到 Excel 在 Excel 中没有产生任何结果
【发布时间】:2013-06-26 04:24:02
【问题描述】:

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

Gridview 毫无问题地出现在我的 .ascx 页面上...我按下按钮执行以下代码,我收到保存或打开的提示,但随后我发现“file.xls”不在格式正确或损坏,我按 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();
        }

【问题讨论】:

标签: c# excel gridview


【解决方案1】:

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

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

在 default.aspx 顶部

这是处理标签之间需要的网格视图所必需的。

另外,由于某些愚蠢的原因,我的 .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 正在显示我的屏幕内容。 我希望这可以帮助其他可能遇到同样问题的人。

【讨论】:

  • 要记住的一点是,输出不是真正的 Excel 电子表格。它本质上是一个可格式化的 HTML/文本文件,导出后需要保存为 excel 电子表格。
  • 好吧,它确实有效,只是我不断收到消息“您尝试打开的文件的格式与文件扩展名指定的格式不同
猜你喜欢
  • 2014-03-18
  • 2023-03-15
  • 2015-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-25
相关资源
最近更新 更多