Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Export GridView records to Excel

0.00/5 (No votes)
5 Sep 2012 1  
In this Article we are going to read and understand how in a web application we can export a gridview data into Excel file. As many times in real

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

In this Article we are going to read and understand how in a web application we can export a gridview data into Excel file. As many times in real time programming we generate reports in the grid format to display to the user.

For example

  1. The list of commodities purchased this month
  2. Reports of SMS Sent.
  3. Reports of invites. etc.and user might want to save this list for the future use in Excel format.

Prerequisites:

  1. To view an Excel workbook file's contents, you must have installed Microsoft Excel (alone or with MS-Office) to view the exported file in your System.
  2. Microsoft Visual Studio (VS) must be installed on the system for development. 

Let's start with creating an application in VS2008 (You can even go for VS2005 or VS2010)

 Following the steps to we are going to follow.

  1. Create a New Project in VS2008 as name it as "ExporttoExcel" in the C# category.
  2. Place a gridview on the default.aspx page and rename it to grdtoexport.
  3. Create a datatable which will bind the grid.
  4. Place a button which will export the grid to excel format.

Code:

protected void Page_Load(object sender, EventArgs e)
{
 //creating a table for the grid use namespace System.Data;
 DataTable  dt = new DataTable ();
 //adding columns to the datatale
 try
 {
 dt.Columns.Add("Srno");
 dt.Columns.Add("Name");
 }
 catch { }
 //adding values to the datatable
 for (int i = 1; i <= 10; i++) 
 {
 DataRow dr = dt.NewRow();
 dr[0] = i;
 dr[1] = "Meetu Choudhary " + i.ToString();
 dt.Rows.Add(dr);
 }
 //binding data table to the grid 
 grdtoexport.DataSource = dt;
 grdtoexport.DataBind();
}

  Writing a ExportToExcel class

  using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;


namespace ExportToExcel
{
 public class ExportToExcel
 {
 public ExportToExcel()
 {
 }
 public void ExportGridView(GridView GridView1, String strFileName)
 {
 PrepareGridViewForExport(GridView1);
 HttpContext.Current.Response.ClearContent();
 HttpContext.Current.Response.Buffer = true;
 HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + strFileName);
 HttpContext.Current.Response.ContentType = "application/ms-excel";
 HttpContext.Current.Response.Charset = "";
 StringWriter sw = new StringWriter();
 HtmlTextWriter htw = new HtmlTextWriter(sw);
 GridView1.RenderControl(htw);
 HttpContext.Current.Response.Write(sw.ToString());
 HttpContext.Current.Response.End();
 }
 
 private void PrepareGridViewForExport(Control gv)
 {
 LinkButton lb = new LinkButton();
 Literal l = new Literal();
 string name = String.Empty;
 for (int i = 0; i < gv.Controls.Count; i++)
 {
 if (gv.Controls[i].GetType() == typeof(LinkButton)) //Link Button Text property
 {
 l.Text = (gv.Controls[i] as LinkButton).Text;
 gv.Controls.Remove(gv.Controls[i]);
 gv.Controls.AddAt(i, l);
 }
 else if (gv.Controls[i].GetType() == typeof(DropDownList))
 {
 l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text; //Drop down Selected Text
 gv.Controls.Remove(gv.Controls[i]);
 gv.Controls.AddAt(i, l);
 }
 else if (gv.Controls[i].GetType() == typeof(CheckBox)) //Convert Check Box to True and False
 {
 l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";
 gv.Controls.Remove(gv.Controls[i]);
 gv.Controls.AddAt(i, l);
 }
 if (gv.Controls[i].HasControls())
 {
 PrepareGridViewForExport(gv.Controls[i]);
 }
 }
 }
 }
}

 

  Calling the Function to export on button click

protected void btnexport_Click(object sender, EventArgs e)
{
 ExportToExcel ex = new ExportToExcel();
 ex.ExportGridView(grdtoexport, "Client.xls"); 
}

 

You can download the code from here


Regards, Meetu Choudhary
Microsoft MVP-ASP/ASP.NET

MsDnM My Forums My Blog

Orignal Article

 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here