【问题标题】:Export to Excel exports the whole webpage and not just the gridview(Sorting enabled)导出到 Excel 导出整个网页,而不仅仅是网格视图(启用排序)
【发布时间】:2023-03-25 20:02:01
【问题描述】:

在我的 C# 应用程序中,我从用户的输入生成一个 Gridview,然后我必须为用户提供一个将 Gridview 导出到 Excel 工作表的选项。

这是我的 abc.aspx 页面:

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

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



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

                    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"

                        ShowFooter="false"
                       AllowSorting="true"
                        OnSorting="GridView1_Sorting"
                        EnableViewState="false"
                       ShowHeaderWhenEmpty="True"
                        AllowPaging="false">
                        <RowStyle Wrap="false" />
                        <HeaderStyle Wrap="false" />
                    </asp:GridView>    
        </div>

    </form>
    <br />  
</body>

这是我的 .cs 页面:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.Script.Services;
using System.Configuration;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using System.IO;

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)
    {

        string fname = filename.Text;


        GridView1.DataSource = (DataSet)Session["data"];
        GridView1.DataBind();
        int rowCount = GridView1.Rows.Count;
        if (rowCount == 0)
        {
            Response.Write("<script>alert('Result Empty!');</script>");
        }
        else
        {
                ExportToExcel(GridView1, fname);
        }
    }



    private void ExportToExcel(GridView GrdView, string fname)
    {

        try
        {
            Response.AddHeader("contentdisposition", "attachment;filename=test1.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.xls";
            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
            GrdView.RenderControl(htmlWrite);
            Response.Write(stringWrite.ToString());
            Response.End();
        }
        catch (Exception ex)
        {
            Response.Write("<script>alert('" + ex.Message + "')</script>");
        }
    }
    public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
    {
    }


    protected void Button1_Click(object sender, EventArgs e)
    {

        string Rname= Page.Request.QueryString["rname"];
        string typeofquery = "my command";

        string abc = null;
       abc = "" + typeofquery + " @RName='" + RName "'";

        SqlDataAdapter cmdldata = new SqlDataAdapter(abc, sqlconn);
        cmdldata.SelectCommand.CommandTimeout = 600;
        dsldata = new DataSet();

        try
        {
            cmdldata.Fill(dsldata);
            Session["data"] = dsldata;
            GridView1.DataSource = dsldata;
            GridView1.DataBind();
        }//end of try
        catch (Exception ex)
        {

            Response.Write(ex);

        }//end of catch

    }

    private const string ASCENDING = " ASC";
    private const string DESCENDING = " DESC";


    public SortDirection GridViewSortDirection
    {
        get
        {
            if (ViewState["sortDirection"] == null)
                ViewState["sortDirection"] = SortDirection.Ascending;

            return (SortDirection)ViewState["sortDirection"];
        }
        set { ViewState["sortDirection"] = value; }
    }


    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        string sortExpression = e.SortExpression;

        if (GridViewSortDirection == SortDirection.Ascending)
        {
            GridViewSortDirection = SortDirection.Descending;
            SortGridView(sortExpression, DESCENDING);
        }
        else
        {
            GridViewSortDirection = SortDirection.Ascending;
            SortGridView(sortExpression, ASCENDING);
        }

    }

    private void SortGridView(string sortExpression, string direction)
    {
        dsldata = (DataSet)HttpContext.Current.Session["data"];
        DataTable dt = dsldata.Tables[0];
        DataView dv = new DataView(dt);
        dv.Sort = sortExpression + direction;
        dt = dv.ToTable();
        DataSet ds1 = new DataSet("table");
        ds1.Tables.Add(dt);
        Session["data"] = ds1;
        GridView1.DataSource = dv;
        GridView1.DataBind();
    }

}

我在我的 gridview 中启用了排序。 问题是:我的整个网页正在导出到 Excel 表。我只想导出我的网格视图。排序工作正常,我在我的 excel 表中得到了新的排序表,但它与整个网页一起使用。 我已经在互联网上的不同地方寻找解决方案。似乎很多人都面临过这个问题。我也尝试过他们的解决方案,例如 更改 Response.ContentType = "application/vnd.xls";到
Response.ContentType = "应用程序/vnd.ms-excel";大多数其他解决方案都类似于我的 ExportToExcel() 函数。

自过去 2 天以来,我一直在研究这件事,但我的应用程序没有任何效果。

请帮忙! 提前谢谢!

更改了我的 ExporttoExcel 函数

private void ExportToExcel(GridView GrdView, string fname)
{

try
{

    Response.Clear();
    Response.AddHeader("content-disposition", "attachment;filename=" + fname + ".xls");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";
    StringWriter stringWrite = new StringWriter();
    HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
    GridView1.RenderControl(htmlWrite);
    Response.Write(stringWrite.ToString());
    Response.End();
}
catch (Exception ex)
{
    Response.Write("<script>alert('" + ex.Message + "')</script>");
}
}

【问题讨论】:

  • 我刚刚意识到,当我在 abc.aspx 页面的 gridview 中删除 OnSorting="GridView1_Sorting" 和 AllowSorting="true" 时,我得到了只有 gridview 的 excel 表。只有当我启用这两个时,问题出现了。请帮忙!

标签: c# asp.net gridview export-to-excel gridview-sorting


【解决方案1】:

我已经解决了这个问题。我意识到问题出在我的 gridview 的 AllowSorting 功能中。我关闭了该页面的事件验证。

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="abc.aspx.cs" Inherits="abc" EnableEventValidation = "false" %>

成功了!

【讨论】:

  • 这对我也有用。 @Ankita 你应该把它标记为答案。
【解决方案2】:

我认为您需要在 Export ToExcel() 函数的顶部使用 Response.Clear()

【讨论】:

  • 我已经编辑了我的 ExportToExcel(已经编辑了我的问题)功能仍然无法正常工作。我该怎么办?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-21
相关资源
最近更新 更多