将2 gridview导出为ex​​cel

时间:2011-12-20 03:26:33

标签: asp.net excel gridview export

我有2个gridview,它的作用类似于产品类别和产品目录。 每个类别都有很少的产品。

现在用户选择了类别并查看产品目录后,我想在excel中导出这两个

示例: 选择产品类别:“水果” 目录是:“Apple,Banana,Orange”

我想存储选定的产品类别以及目录。

目前,我只能导出产品目录列表。(将1 gridview简单导出为ex​​cel)

我希望我能说清楚。

我在asp.net c#上运行

单击按钮上的当前代码

 string filename = String.Format("Survey Results_{0}_{1}.xls",
    DateTime.Today.Month.ToString(), DateTime.Today.Year.ToString());

    Response.Clear();
    Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
    Response.Charset = "";

    // SetCacheability doesn't seem to make a difference (see update)
    Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);

    Response.ContentType = "application/vnd.xls";

    System.IO.StringWriter stringWriter = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);

    // Replace all gridview controls with literals
    ClearControls(GridView2);

    // Throws exception: Control 'ComputerGrid' of type 'GridView'
    // must be placed inside a form tag with runat=server.
    // ComputerGrid.RenderControl(htmlWrite);

    // Alternate to ComputerGrid.RenderControl above
    System.Web.UI.HtmlControls.HtmlForm form
        = new System.Web.UI.HtmlControls.HtmlForm();
    Controls.Add(form);

    form.Controls.Add(GridView2);
    form.RenderControl(htmlWriter);

    Response.Write(stringWriter.ToString());
    Response.End();

1 个答案:

答案 0 :(得分:0)

也许您可以尝试通过加入结果在gridview中构建动态codebehind,而不是输出gridview2,您必须导出动态生成的gridview。< / p>