By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,685 Members | 1,031 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

How to export a GridView Data to Excel

P: 17
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 "btnExportToExcel"
3. Write a code in aspx.cs file

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. using System.Data;
  8. namespace ExampleOnAjax
  9. {
  10.     public partial class ExportFiles : System.Web.UI.Page
  11.     {
  12.         protected void Page_Load(object sender, EventArgs e)
  13.         {
  14.             DataTable dtRecords = new DataTable();
  15.             dtRecords.Columns.Add("State", typeof(string));
  16.             dtRecords.Columns.Add("City", typeof(string));
  17.             DataRow dr = dtRecords.NewRow();
  18.             dr["State"] = "Karnataka";
  19.             dr["City"] = "Bangalore";
  20.             dtRecords.Rows.Add(dr);
  21.  
  22.             grdData.DataSource = dtRecords;
  23.             grdData.DataBind();
  24.         }
  25.  
  26.         protected void btnExportToExcel_Click(object sender, EventArgs e)
  27.         {
  28.             Response.Clear();
  29.             Response.ContentType = "application/ms-excel";
  30.             Response.Charset ="";
  31.             Page.EnableViewState = false;
  32.             Response.AddHeader("Content-Disposition", "inline;filename=report.xls");
  33.             System.IO.StringWriter tw = new System.IO.StringWriter();
  34.             System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
  35.             grdData.RenderControl(hw);
  36.             Response.Write(tw.ToString());
  37.             Response.End();
  38.         }
  39.         public override void VerifyRenderingInServerForm(Control control)
  40.         {
  41.  
  42.         }
  43.  
  44.  
  45.     }
  46. }
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.
May 9 '11 #1
Share this Article
Share on Google+