Tuesday, August 9, 2011

.NET and ASP.NET interview questions: - How to Export GridViewData to Excel in .NET?

This is one of the most important topics while dealing with GridView data so I
thought to share this information.

Let’s do a small demonstration to see how exactly we can export data of GridView
to Excel in .NET.

In order to Export Data of GridView to Excel you need to follow the following

Step1: - create a new web application for that go to File > New > Project
> Select ASP.NET Empty Web Application.

Now, add a WebForm in your application for that justgo to Solution Explorer
>Right click on the Project > Add > Add New Item > Select WebForm.

Now, on the WebForm.aspx page just drag and drop GridView control and do the same as I have done in below code snippet.







Step2: -In this step we will bound the data to the GridView control.

In order to bound the data go to WebForm.aspx.cs and add the below code snippet.



SqlConnection connection = newSqlConnection(ConnectionString);


SqlCommandcommmand = newSqlCommand();

com.CommandText = "select FirstName,LastName from Customers";

com.Connection = connnection;


SqlDataAdapter adapter = newSqlDataAdapter(commmand);

DataSet dataset = newDataSet();


GridView1.DataSource = dataset;


Later just call the method LoadGrid() on form load event like below code snippet.

protectedvoidPage_Load(object sender, EventArgs e)


if (!IsPostBack)





: - Now again go to WebForm.aspx and add a Button control on the Form and name it as ExportToExcel.


Now on the Button click event just add the below code snippet.

protectedvoid Button1_Click(object sender, EventArgs e)



Response.AddHeader("content-disposition", "attachment;filename=Customer.xls");

Response.Charset = "";


Response.ContentType = "application/vnd.xls";

System.IO.StringWriterstringWrite = newSystem.IO.StringWriter();

System.Web.UI.HtmlTextWriterhtmlWrite = newHtmlTextWriter(stringWrite);

StringWriterswriter = newStringWriter();

HtmlTextWriterhwriter = newHtmlTextWriter(swriter);

HtmlFormfrm = newHtmlForm();


frm.Attributes["runat"] = "server";






Once you have completed the above steps now just run your application.
As soon as you click on Export to Excel Button a window will pop up like below

Just click on open a new window will pop up like below diagram.

Now just click yes your data of GridView will be nowbeing exported to the Excel
and will appear like below diagram.

View the following video on ASP.NET Web.config transformation: -

Click for more learning interview tutorials on .NET and ASP.NET interview questions
Visit author’s blog on .NET and ASP.NET interview questions

No comments: