Would you like to get paid for signing up for a web hosting plan with Bluehost.com?
Powered by MaxBlogPress 

Bluehost - Affordable, Reliable Web Hosting Solutions
Powered by MaxBlogPress 

Export GridView Data to MS-Excel

Posted on October 6, 2008
Filed Under Development, Programming |

If you've enjoyed reading this post then please subscribe to my Full Text RSS Feed.

If you have the requirement to export data content from a GridView to a spreadsheet, i.e. MS-Excel, you have come to the right place.

It is not difficult to code this requirement in ASP.NET.

Here is an example of a GridView with data from the product table in SQL Server. A product search functionality is added to filter the product data displayed in the GridView.


The GridView is databound and the databound fields are Model and Serialized. The SelectCommand is “SELECT Model, Serialized FROM Product ORDER BY Model”. The Export to Excel button will trigger the Event to export the selected data in the GridView into MS-Excel.

In the code-behind, call the Method ExportGridView within Button3_Click (see below). Button3_Click is fired when the button “Export to Excel” is clicked.

Add Using System.IO and Using System.Text namespaces at the top of the code-behind page. We will be using some of the classes when exporting to MS-Excel.

Since this is a browser-type application, it is important is to define the correct header and contenttype. e.g.

Response.AddHeader(”content-disposition”, attachment);
Response.ContentType = “application/ms-excel”;

So that the server side will know that the content type is MS-Excel and not html. And the server respond with a file attachment named Product.xls.

The StringWriter class is derived from System.IO class and the HtmlTextWriter class is derived from System.Web.UI namespace.

Create a new instance of another GridView - GridView GridView2 = new GridView(). If you use the GridView1 instance, it will not work although the code will compile.

The if condition that checks the TextBox1.Text is to determine if we need to apply the search filter.

Then bind the SQL data source to the send GridView (GridView2) and render the content in the browser using Response.Write(sw.ToString()).

That completes this example.

Sphere: Related Content

Other Related Posts:

  • Ways to convert Pdf to Word
  • Adding CheckBox in GridView
  • Beginning Ajax with Visual Studio 2005
  • Merging Datasets
  • Bind data to DropDownList using a DataTable

  • If you've enjoyed reading this post then why not subscribe to received updates by email.

    Enter your email address:

    Delivered by FeedBurner

    Email This Post Email This Post

    Trackback This Post

    Comments

    Leave a Reply