简体   繁体   English

通过单击提交按钮将gridview导出到excel工作表

[英]export the gridview to excel sheet by clicking on submit button

I am creating ac# application. 我正在创建ac#应用程序。 In this application I take inputs from user and using those entries I fire a sql query and dispay the results in the Gridview. 在此应用程序中,我从用户处获取输入,并使用这些条目触发sql查询并在Gridview中支付结果。 So these actions happen when we click on submit button. 因此,当我们单击“提交”按钮时,就会发生这些操作。 After this, I want to give the user an option to export the gridview results to an excel sheet by clicking on another submit button. 之后,我想给用户一个选项,通过单击另一个提交按钮将gridview结果导出到Excel工作表。 the code for these things is: 这些东西的代码是:

aspx code: aspx代码:

     <body>
        <form id="form1" runat="server">
            <div>
                <b>Enter Value 1 :</b>
                <asp:TextBox ID="p1" runat="server" />
                <br />

                <b>Enter value 2 :</b>
                <asp:TextBox ID="p2" runat="server" /><br />

                <asp:Button ID="btn1" runat="server" OnClick="Button1_Click" Text="Start Search" />
                 <asp:Button ID="btn2" runat="server" OnClick="Button2_Click" Text="Export Data to Excel" />
                <hr />

                        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"
                            OnPageIndexChanging="gridView_PageIndexChanging"
                            ShowFooter="false"
                            CssClass="gridstyle"
                            EnableViewState="false"
                            AllowPaging="true">
                            <AlternatingRowStyle CssClass="altrowstyle" />
                            <HeaderStyle CssClass="headerstyle" />
                            <RowStyle CssClass="rowstyle" />
                            <RowStyle Wrap="false" />
                            <HeaderStyle Wrap="false" />
                        </asp:GridView>
            </div>
        </form>
    </body>

The code file for this code is: 该代码的代码文件为:

    public partial class pSearch : System.Web.UI.Page
    {
    SqlConnection sqlconn = new  SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString);
    DataSet dsldata;
    protected void Page_Load(object sender, EventArgs e)
    {

    }


    protected void Button2_Click(object sender, EventArgs e)
    {
        DataSet ds0 = new DataSet();
        ds0 = (DataSet)Session["data"]; 
        DataView dataview_ldata = dsldata.Tables[0].DefaultView;
        DataTable dt = dsldata.Tables[0];
        GridView1.DataSource = dataview_ldata;
        GridView1.DataBind();
        ExportToExcel(GridView1);

    }



    private void ExportToExcel(GridView GrdView)
    {
        try
        {
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
            Response.Charset = "";
            // If you want the option to open the Excel file without saving than
            // comment out the line below
            // Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/vnd.xls";
            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            GrdView.RenderControl(htmlWrite);
            Response.Write(stringWrite.ToString());
            Response.End();
        }
        catch (Exception ex)
        {
            Response.Write("<script>alert('" + ex.Message + "')</script>");
        }
    }



    protected void Button1_Click(object sender, EventArgs e)
        {

        string RName = Page.Request.QueryString["RName"];
        string typeofquery = "mycommand";
        string pv1 = p1.Text ;
        string pv2 = p2.Text ;
        string abc = null;
        abc = "" + typeofquery + " @RName=" + RName + ",@P1='" + pv1 + "',@P2='" + pv2 + "'";
        SqlDataAdapter cmdldata = new SqlDataAdapter(abc, sqlconn);

        GridView1.PageSize = 1000;


        cmdldata.SelectCommand.CommandTimeout = 600;
         dsldata = new DataSet();
        ErrorHandling errhandle = new ErrorHandling();
        try
        {
            cmdldata.Fill(dsldata);
            Session["data"] = dsldata;

            DataView dataview_ldata = dsldata.Tables[0].DefaultView;
            DataTable dt = dsldata.Tables[0];
            GridView1.DataSource = dataview_ldata;
            GridView1.DataBind();

        }//end of try
        catch (Exception ex)
        {
            String errorMessage = errhandle.displayException(ex);
            Response.Write(errorMessage);

        }//end of catch
        finally
        {
            if (errhandle != null)
            {
                errhandle = null;
            }
        }//end of finally
    }

      public override void VerifyRenderingInServerForm(Control control)
    {

        // Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.

    }

    protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataBind();
    }

    }

I am getting an empty excel sheet right now as my output. 我现在正在输出一个空白的Excel工作表。

From my anaysis I think the following is the problem: When button 1 is clicked Gridview is generated by the query.When button 2 is clicked , all the data that It had previously is lost (even though we can still see it on the screen).That is why I am getting an empty excel sheet right now. 从我的分析来看,我认为这是问题所在:单击按钮1时,查询将生成Gridview。单击按钮2时,它以前拥有的所有数据都会丢失(即使我们仍然可以在屏幕上看到它)这就是为什么我现在得到一个空的Excel工作表的原因。

Secondly,Since I am creating the gridview on button click and not on the page load,the data of the gridview is not available in the protected void Button2_Click(object sender, EventArgs e){} function. 其次,由于我是在单击按钮而不是在页面加载时创建gridview的,因此在受保护的void Button2_Click(object sender,EventArgs e){}函数中,gridview的数据不可用。

Only option now to make it working is I should do the same operations of executing the query again on button2_Click function also. 现在唯一使它起作用的选项是我也应该对button2_Click函数再次执行相同的查询操作。

But again I don't think this is an efficient way.And moreover I am running a complex query that may take 3 -4 mins at times to give the output.So running the query two times is out of question. 但是我也不认为这是一种有效的方法,而且我正在运行一个复杂的查询,该查询有时可能需要3 -4分钟才能给出输出,因此两次运行该查询是毫无疑问的。 I also tried caching the dataset but it did not work.Even creating session in not working. 我也尝试过缓存数据集,但是它没有用,即使创建会话也没有用。

I have been breaking my head on this since last 1 day. 从过去的1天开始,我一直在为此打碎头。 Please help me! 请帮我! Thank you. 谢谢。

Cache sounds like a good solution, could you post your cache code? 缓存听起来是个不错的解决方案,您可以发布缓存代码吗?

Otherwise, I would do it in ViewState. 否则,我将在ViewState中执行此操作。 Get the result of your long query, store it in ViewState, bind the result to the GridView, then after your button click, you can access the ViewState-stored data. 获取长查询的结果,将其存储在ViewState中,将结果绑定到GridView,然后单击按钮后,即可访问ViewState存储的数据。 This isn't the best way to do it for large sets of data, because ViewState is sent across the wire with each PostBack and stored on the client side. 这不是对大量数据进行处理的最佳方法,因为ViewState与每个PostBack一起通过网络发送并存储在客户端。 It can really slow your application down and cause unexpected errors. 这确实会使您的应用程序变慢,并导致意外错误。

Here's my edit, that I got working locally: 这是我在本地工作的编辑:

Storing it in Session should work fine. 将其存储在Session中应该可以正常工作。 Here's what I did with some dummy data. 这是我对一些虚拟数据所做的。 FYI, you can bind a GridView directly to a DataSet, you don't have to drill down to a DataTable or anything like that. 仅供参考,您可以将GridView直接绑定到DataSet,而不必深入到DataTable或类似的东西。

        protected void Button1_Click(object sender, EventArgs e)
        {

            string RName = Page.Request.QueryString["RName"];
            string typeofquery = "mycommand";
            string pv1 = p1.Text;
            string pv2 = p2.Text;
            string abc = null;
            abc = "" + typeofquery + " @RName=" + RName + ",@P1='" + pv1 + "',@P2='" + pv2 + "'";
            SqlDataAdapter cmdldata = new SqlDataAdapter(abc, sqlconn);

            GridView1.PageSize = 1000;


            cmdldata.SelectCommand.CommandTimeout = 600;

            var dummyDt = new DataTable();
            dummyDt.Columns.Add("Sup");
            dummyDt.Columns.Add("Bro");

            dummyDt.Rows.Add("Test1", "test2");
            dummyDt.Rows.Add("Test1", "test2");
            dummyDt.Rows.Add("Test1", "test2");
            dummyDt.Rows.Add("Test1", "test2");
            dummyDt.Rows.Add("Test1", "test2");

            dsldata = new DataSet();
            dsldata.Tables.Add(dummyDt);
            //ErrorHandling errhandle = new ErrorHandling();
            try
            {
                //cmdldata.Fill(dsldata);
                Session["data"] = dsldata;

                //DataView dataview_ldata = dsldata.Tables[0].DefaultView;
                //DataTable dt = dsldata.Tables[0];
                GridView1.DataSource = dsldata;
                GridView1.DataBind();

            }//end of try
            catch (Exception ex)
            {
                //String errorMessage = errhandle.displayException(ex);
                Response.Write(ex.Message);

            }//end of catch
            finally
            {
                //if (errhandle != null)
                //{
                //    errhandle = null;
                //}
            }//end of finally
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            //DataSet ds0 = new DataSet();
            //ds0 = ;
            //DataView dataview_ldata = dsldata.Tables[0].DefaultView;
            //DataTable dt = dsldata.Tables[0];
            GridView1.DataSource = (DataSet)Session["data"];
            GridView1.DataBind();
            ExportToExcel(GridView1);

        }

        private void ExportToExcel(GridView GrdView)
        {
            try
            {
                Response.Clear();
                Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
                Response.Charset = "";
                // If you want the option to open the Excel file without saving than
                // comment out the line below
                // Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.ContentType = "application/vnd.xls";
                System.IO.StringWriter stringWrite = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
                GrdView.RenderControl(htmlWrite);
                Response.Write(stringWrite.ToString());
                Response.End();
            }
            catch (Exception ex)
            {
                Response.Write("<script>alert('" + ex.Message + "')</script>");
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM