简体   繁体   English

在ASP.NET C#中导出到Excel后如何显示Gridview?

[英]How to show Gridview after exporting to Excel in asp.net c#?

I have wrote a program where the requirement is to when user select particular date then should show one report. 我编写了一个程序,要求用户选择特定日期时应显示一份报告。 And here the report I am showing is in Gridview in a separate page under button click even. 在这里,我显示的报告在Gridview的单独页面中,甚至在按钮单击下。 But now it is required to download the report at the same time they click to view and store into some particular folder. 但是,现在需要在他们单击以查看并存储到某些特定文件夹的同时下载报告。 So, I have written the below code and it is working to download the report into excel format into the particular folder but I cannot see the gridview anymore. 因此,我编写了以下代码,并且正在将报告以excel格式下载到特定的文件夹中,但是我再也看不到gridview了。 I have put the below function into the pageload after binding data with the gridview but now I can see that while debuging the pointer coming to the binding grid and exporting excel again and again and the page shows error " The Web Page cannot be displayed." 在使用gridview绑定数据之后,我将以下函数放入了页面加载中,但是现在我可以看到,调试指向绑定网格的指针并一次又一次导出excel时,页面显示错误“无法显示Web页面”。 Please help me on this how may I fix this. 请帮我解决这个问题。

Here is my code example to write into excel and store into a location: 这是我写到excel并存储到位置的代码示例:

     private void ExportPagetoExl()
{
    Response.Clear();
    Response.Buffer = true;
    if (string.IsNullOrEmpty(cpIdStr))
        Response.AddHeader("content-disposition", "attachment;filename="+ Request["year"] +"_" + Request["month"] + "_Transaction_" + requestChannel + ".xls");
    else
    {
        Response.AddHeader("content-disposition", "attachment;filename=" + Session["cpUsername"] + "_" + Request["year"] + "_" + Request["fullmonth"] + "_" + requestChannel + ".xls");
    }

    Response.Charset = string.Empty;
    Response.ContentType = "application/vnd.ms-excel";

    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    FileInfo FI = new FileInfo(@"C:\MyPC\Projects\report\transaction_" + requestChannel + "_" + Request["year"] + "_" + Request["fullmonth"] + ".xls");
    GridView1.AllowPaging = false;
    GridView1.DataSource = myData.DefaultView;
    GridView1.DataBind();


    try
    {
        GridViewRow header = GridView1.HeaderRow;
        GridView1.RenderControl(hw);
        string style = "<style>.textmode{mso-number-format:\\@;}</style>";
        string directory = @"C:\MyPC\Projects\report\";
        if (!Directory.Exists(directory))
        {
            Directory.CreateDirectory(directory);
        }

        System.IO.StreamWriter vw = new System.IO.StreamWriter(@"C:\MyPC\Projects\report\" + Request["year"] + "_" + Request["month"] + "_Transaction_" + requestChannel + ".xls", true);
        sw.ToString().Normalize();
        vw.Write(sw.ToString());
        vw.Flush();
        vw.Close();
        Response.Flush();
        Response.BufferOutput = true;
        Response.Close();
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
    }
}

Thanks in advance. 提前致谢。

ASPX Code ASPX代码

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="js/jquery.min.js"></script>
        <script type="text/javascript">
            function ExportExcel() { //function to be executed from server side after gridview is bound
                $('#btnexport').click();
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:Button ID="btnsubmit" Text="Submit" runat="server" ClientIDMode="Static" OnClick="btnsubmit_Click" />
                <asp:Button ID="btnexport" runat="server" ClientIDMode="Static" style="display:none;" OnClick="btnexport_Click" /><!--Hidden button  -->
                <asp:GridView ID="Gridview1" runat="server"></asp:GridView>
            </div>
        </form>
    </body>
    </html>

Code Behind 背后的代码

    protected void btnsubmit_Click(object sender, EventArgs e)
    {
        //Bind Gridview
        LoadGridview();
        //Call "ExportExcel();" Javascript function which has been defined in the aspx page 
        ScriptManager.RegisterStartupScript(this, this.GetType(), "com", "ExportExcel();", true);
    }

    protected void btnexport_Click(object sender, EventArgs e)
    {
        //export the file here
        ExportToExcel();
    }
    private void LoadGridview()
    {
        //Your code to bind gridview goes here
    }
    private void ExportToExcel()
    {
        //Your code to export goes here
    }

Explanation 说明

  1. You have your main button "btnsubmit", on click of which, the gridview will be populated. 您有主按钮“ btnsubmit”,单击该按钮将填充gridview。
  2. Create a hidden button "btnexport", set its style to display none so that it won't be visible to user. 创建一个隐藏的按钮“ btnexport”,将其样式设置为不显示任何样式,以使用户看不到它。 On its click event, write the code to export the excel. 在单击事件上,编写代码以导出excel。
  3. On your aspx page define a function "ExportExcel(){}" which will dynamically call the click event of the hidden button. 在aspx页面上,定义一个函数“ ExportExcel(){}”,该函数将动态调用隐藏按钮的click事件。
  4. When user clicks the "btnsubmit", on the server side, The code binds Gridview & executes "ExportExcel" using "ScriptManager.RegisterStartupScript" 当用户单击服务器端的“ btnsubmit”时,该代码将绑定Gridview并使用“ ScriptManager.RegisterStartupScript”执行“ ExportExcel”
  5. ExportExcel, inturn, executes the click event of "btnexport" which has the code to export the excel to browser. 反过来,ExportExcel执行“ btnexport”的单击事件,该事件具有将excel导出到浏览器的代码。
  6. Don't forget to have Jquery reference. 不要忘记拥有Jquery参考。

You need to change the way of doing it. 您需要更改执行方式。

  • Create a page which has Gridview to show the data and add a control (either ActionLink or Button) to Export the data to excel beside it. 创建一个具有Gridview来显示数据的页面,并添加一个控件(ActionLink或Button)以将数据导出到旁边的excel。
  • Now use the default view to show the grid which is GridView1 现在使用默认视图显示网格为GridView1
  • Put your code which is responsible to generate Excel in another method and call that method on button or ActionLink click.And use GridView2 for generating excel rather GridView1. 将负责生成Excel的代码放在另一个方法中,然后在按钮上单击该链接或单击ActionLink单击该方法。然后使用GridView2生成excel而不是GridView1。

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

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