Skip to content

How to export datagridview contents to excel

niti bid

Asked Dec 5, 2007, 8:45 PM EST1 answer
Share
LinkedInX

I have to export the data present in the datagridview to Microsoft Excel.  It is a window application using c#.  Does anyone know how to do it.  Please help.

Thanks

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0

    This Datagrid to Excel:

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    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.IO;

    public partial class ExcelSheet_ExportExcel : System.Web.UI.Page
    {
        GridView grdStudentMarks = new GridView();
        Button btnExportToGrid = new Button();

        protected void Page_Load(object sender, EventArgs e)
        {
           
            // SqlDataSource sds = new SqlDataSource(@"Data Source=Master\SQLEXPRESS; Initial Catalog=shan; User Id=shan; Password=Raju", "select * from MarkSheet");
           
           
            grdStudentMarks.DataSource = sds;
            grdStudentMarks.DataBind();
           // Form.Controls.Add(grdStudentMarks);
            Form.Controls.Add(btnExportToGrid);
           
            string path = Context.Server.MapPath("Download.aspx");
            btnExportToGrid.Text = "Export To Grid ";
            btnExportToGrid.Click += new EventHandler(this.btnExportToGrid_Click);
        }
        void btnExportToGrid_Click(object sender, EventArgs e)
        {
            ExportGridToExcel(grdStudentMarks, "DynamicsDunction");
        }
        private void ExportGridToExcel(GridView grdGridView, string fileName)
        {
            IList list = new ArrayList();

            Response.Clear();

            Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", fileName));
            Response.Charset = "";

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

            StringWriter stringWrite = new StringWriter();
            HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

            grdGridView.RenderControl(htmlWrite);

            Response.Write(stringWrite.ToString());
            Response.Flush();
            Response.End();

        }
        public override void VerifyRenderingInServerForm(Control control)
        {

        }
    }

    0