.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal

Home >> Articles >> ASP.NET >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Export GridviewData to Excelsheet using ASP.Net

Posted By:Syed Shakeer Hussain       Posted Date: June 19, 2010    Points: 20    Category: ASP.NET    URL: http://www.dotnetspark.com  

This Article Exlains you how to Export a Gridview Data to Excel

In this Article you can Know how to Export a Gridview Data to Excel .
Bind the Data to the Gridview using SqlDatSource and one Button on the webpage.

How to Create a Excel sheet?

'TextWriter' class 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.
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.



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

 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend