Simplest Method Export GridviewData to Excelsheet using ASP.Net

Posted by in ASP.NET category on for Intermediate level | Views : 9932 red flag

In this Article you can Know how to Export a Gridview Data to Excel sheet using IO strems.

Bind the Data to the Gridview using SqlDatSource and one Button on the webpage.

How to Create a Excel sheet?

is used to Create a Excel Sheet by creting the StreamWriter class object.StreamWriter
class takes the path the of the excel sheet name as argument.Dont forget to use
the verbatile string (@) at the beginning of the path as follows:

TextWriter sw = new StreamWriter(@"F:\\ExcelData.xls");


The Extension of the Excel Sheet is .xls.It will automatically creats the excel
sheet with the name ExcelData in ‘F’Drive.If the Excel sheet is already
existing with the name ‘ExcelData’ it will overrides the Data.

in .asp.cs page

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.IO;

public partial class _Default : System.Web.UI.Page


    protected void Page_Load(object sender, EventArgs e)





//Double click your Button and write the below code to Export Gridview Data to Excel

    protected void Button1_Click(object sender, EventArgs e)


    TextWriter sw = new StreamWriter(@"F:\\ExcelData.xls");

    //Getting the Gridview HeaderRow Values




        for (int i = 0; i < GridView1.Rows.Count; i++)


            //Getting the Gridview Row values

            sw.WriteLine(GridView1.Rows[i].Cells[0].Text  + "\t " + GridView1.Rows[i].Cells[1].Text  + "\t" + GridView1.Rows[i].Cells[2].Text );


        sw.Close();//Don’t Forget to Close the StreamWrtier object.



output of Excel sheet with data.

The Following Error occurs when you try to export a Data to Excel when the Excel Sheet is in open State.

Error Iamge.

Page copy protected against web site content infringement by Copyscape

About the Author

Full Name: Syed Shakeer Hussiain P
Member Level:
Member Status: Member
Member Since: 2/5/2009 3:12:18 AM
Country: India
Syed Shakeer Hussain
Shakeer Hussain has completed his Master of Computer Applications degree from Deccan College of engg and technology of Osmania University.He is a MVM of has good experience in the areas of ASP.NET, C#.NET, VB.NET, SQL SERVER 2000/2005 and Windows Mobile. He has worked in Windows Mobile,Web Applicatin and ERP projects.

Login to vote for this post.

Comments or Responses

Posted by: Ksuresh on: 10/6/2012 | Points: 25
Hi Syed Shakeer,

Gridview1.Rows[i].Cells[1].Text and all rows and cell values showing empty value what is the reason but Rows count showing correctly


Posted by: Karthikreddy on: 2/8/2013 | Points: 25
its not working

Login to post response

Comment using Facebook(Author doesn't get notification)