将gridview内容导出到Excel,div和asp:content的问题

时间:2013-11-22 15:28:09

标签: c# asp.net excel html gridview

我有以下问题,直到昨天我的网络应用程序工作正常,我已经/在我的内容页面中(一切正常):

  • 查询按钮,将结果显示在我唯一的网格视图中
  • 导出到Excel的内容按钮,将gridview内容导出到Excel
  • 将gridview作为电子邮件附件发送的电子邮件按钮

在我的母版页上,我有一个带有asp:contentplaceholder的div类,然后在我的内容页面上,我在主页面上调用带有占位符id的asp:content,内容页面上的此部分包含booth按钮以及gridview,但是,由于我的查询显示了数千条记录,我想让网格视图在高度上滚动。

为了实现这一点,我创建了另一个div类,其中包含一切,给它一个名称,并在css上修改它的大小并使其可滚动,然后我在可滚动的asp:content部分内拖动gridview。 gridview显示查询结果很好,它可以像我想要的那样滚动,但是,当我尝试将gridview内容导出为ex​​cel或发送带有excel附件的电子邮件时,excel在两种情况下都是空的,我没有更改导出到excel按钮,有什么可能搞乱导出?

我要发布相关的代码:

excel按钮

protected void Buttonexcel_Click(object sender, EventArgs e)
{

    try
    {
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/vnd.ms-excel";
        Response.Charset = "";
        Response.AddHeader("content-disposition", "attachment;filename=dados.xls");
        StringWriter sWriter = new StringWriter();
        HtmlTextWriter hWriter = new HtmlTextWriter(sWriter);
        GridView1.RenderControl(hWriter);
        Response.Output.Write(sWriter.ToString());
        Response.Flush();
        Response.End();
    }
    catch (Exception ex)
    {
        Label1.Text = ex.ToString();
    }

}
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered, tem a ver com o botão de exportação para excel*/
}

主页面部分包含按钮和gridview

<div class="span8"><asp:ContentPlaceHolder ID="rightcontent" runat="server"></asp:ContentPlaceHolder></div><div class="scrollable"><asp:ContentPlaceHolder ID="rightcontentdown" runat="server"></asp:ContentPlaceHolder></div>

包含按钮和gridview的内容页面部分,我在这里有一个表单标签,标签是否会导致导出无法正常工作?

somehow the editor won't let post the entire code

1 个答案:

答案 0 :(得分:0)

我认为你在绑定gridview之前调用Buttonexcel_Click事件或者你的Binding方法在里面(!Page.Postback),但是请尝试下面的代码我在按钮点击事件中再次填充gridview。然后将其导出为ex​​cel。

试试这个

      string attachment = "attachment; filename=xxxx" + DateTime.Now + ".xls";
                Response.ClearContent();
                Response.AddHeader("content-disposition", attachment);
                Response.ContentType = "application/ms-excel";
                datatable dt = new datatable();
                  // dt =  Your query to get result 

                using (StringWriter sw = new StringWriter())
                {
                    using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                    {                 
                        GridView1.DataSource = dt;//Bind your gridview 
                        GridView1.DataBind();
                        dg.RenderControl(htw);
                        Response.Write(sw.ToString());
                        Response.End();
                    }
                }