Add an “Export to Excel” button to a webpage to export gridview to excel in webapplication

后端 未结 2 1966
借酒劲吻你
借酒劲吻你 2021-01-16 02:50

i built a patient management software for a clinic and i need to export patiet list from ASP.net grid view to excel file

my question is:

Is there a way to ex

2条回答
  •  时光取名叫无心
    2021-01-16 03:20

    first you have to add the following to the page directive to avoid runtime error

     EnableEventValidation ="false"
    

    add gridview to aspx page the session "dsource" is passing the datasource from advanced search page containing the connection string and select command then here is the code behind


    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Data.SqlClient;
    using System.Threading;
    using System.IO;
    using System.Reflection;
    
    public partial class csresults : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    
        gridview1.DataSource = Session["dsource"];
        gridview1.DataBind();
    
    
    
    
    }
    
    
      public override void VerifyRenderingInServerForm(Control control)
    {
    
    }
    
    
    
    protected void Button2_Click(object sender, EventArgs e)
    {
        HtmlForm form = new HtmlForm();
        string attachment = "attachment; filename=Patients.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter stw = new StringWriter();
        HtmlTextWriter htextw = new HtmlTextWriter(stw);
        form.Controls.Add(gridview1);
        this.Controls.Add(form);
        form.RenderControl(htextw);
        Response.Write(stw.ToString());
        Response.End();
    }
    

    }

提交回复
热议问题