How to export a GridView Data to Excel

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vivek kapile
    New Member
    • Mar 2011
    • 17

    How to export a GridView Data to Excel

    Language: ASP.net
    Platform: Visual Studio 2008 with ASP.net
    Technology: Used in ASP.net

    Introduction

    1. Add a gridview into a aspx file
    2. Add a button into a aspx file and give the name as "btnExportToExc el"
    3. Write a code in aspx.cs file

    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    namespace ExampleOnAjax
    {
        public partial class ExportFiles : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                DataTable dtRecords = new DataTable();
                dtRecords.Columns.Add("State", typeof(string));
                dtRecords.Columns.Add("City", typeof(string));
                DataRow dr = dtRecords.NewRow();
                dr["State"] = "Karnataka";
                dr["City"] = "Bangalore";
                dtRecords.Rows.Add(dr);
    
                grdData.DataSource = dtRecords;
                grdData.DataBind();
            }
    
            protected void btnExportToExcel_Click(object sender, EventArgs e)
            {
                Response.Clear();
                Response.ContentType = "application/ms-excel";
                Response.Charset ="";
                Page.EnableViewState = false;
                Response.AddHeader("Content-Disposition", "inline;filename=report.xls");
                System.IO.StringWriter tw = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
                grdData.RenderControl(hw);
                Response.Write(tw.ToString());
                Response.End();
            }
            public override void VerifyRenderingInServerForm(Control control)
            {
    
            }
    
    
        }
    }
    Summary:
    Run the application click on button, it will ask to save or open a file, if you save it will be saved into your disk
    or if you click on open it directly open the excel file.
    Last edited by Niheel; May 24 '11, 11:48 PM. Reason: Code tags added. Email id removed
Working...