Introduction

To show data in a GridView is a good way of displaying data, but it becomes difficult to manipulate and filter large amounts of data in a GridView. Exporting data to an Excel file is a great solution to handle large amounts of data because Excel gives many features like sorting, searching, filtering, etc., without writing a single line of code.

In this example, I will show:

How to pull data from the database and display it in a grid.

How to export data from a grid to an Excel file.

How to export data from a datareader to an Excel file.

How to handle large data and combat with different types of errors.

Using the Code

This sample is uses ASP.NET 2.0, C#, and SQL Server 2005.

I am using a simple form of database table to avoid unnecessary overheads. Let us assume that we have a database named "UniversityManager" and it has a table named "Student". The structure of the table is as follows:

Column Name

Data Type

Roll

varchar(10)

Name

varchar(50)

Marks

int

I am using an ASP.NET SqlDataSource control to pull the data from the database. SqlDataSource can be used as a data source which can fetch data from the database, and it can be bound to an ASP.NET control. For showing this data in a grid, I am using the ASP.NET GridView control. The GridView control is the successor to the DataGrid control. Like the DataGrid control, the GridView control was designed to display data in an HTML table. When bound to a data source, the DataGrid and GridView controls each display a row from a DataSource as a row in an output table.

When the ASP.NET page is rendered, "grdStudentMarks" would be populated with data from the "student" table of the "UniversityManager" database. Hence Windows authentication is used. Besides this, I have two buttons named "btnExportFromDatagrid" and "btnExportFromDataset".

Now we have a grid full of data from the database. Our next objective is to export this data from the DataGrid to Excel. We have written this code in the Click event of "btnExportFromDataGrid".

When the button is clicked, we invoke a function ExportGridToExcel with Gridview as a parameter and the name of the file that we wish to save. A header is added to the HttpResponse stream. It will force the user to download the file, instead of displaying it embedded in the browser (in IE). Then, with Response.ContentType, we set the HTTP MIME Type of the output stream to "application/vnd.xls". Then, the RenderControl method of the GridView class is used, which outputs the server control content to the provided HtmlTextWriter, which is htmlWrite. Finally, this is written to the response stream.

The job is supposed to be done at this stage! But when you load the page and click the button, you would probably see the following error:

"Control 'grdStudentMarks' of type 'GridView' must
be placed inside a form tag with runat=server."

To resolve this error, you should override the VerifyRenderingInServerForm method. Just write the following:

publicoverridevoid VerifyRenderingInServerForm(Control control)
{
}

That's it! The data in the GridView would be exported to the Excel file which would be saved at the desktop.

But there are some problems with this solution:

If you use paging in your GridView, then only the data of individual pages would be exported instead of the data of the whole grid. That means only those data would be exported which are rendered within the page.

If the data in the GridView is huge, you would probably get the following error:

"Timeout expired. The timeout period elapsed prior
to completion of the operation or the server is not responding."

This is a System.Data.SqlClient.SqlException. This exception occurs when the timeout period elapses prior to the completion of the operation.

To solve this type of problem, we would use the following solution:

Solution

I am going to use the SQLCommand class because by using it, we can set a timeout property. The "CommandTimeout" property sets the wait time before terminating any execute command. The data is taken in SqlDataReader and each row of the data reader is written in the response stream. One thing to mention is that the value of each cell (a particular column of a row) is followed by a comma (,) delimiter so that the CSV file can format it.

It would solve the problem of having to download large data. The problem of the SQLClient timeout exception is solved, but there is still a possibility to get an HtttpRequest timeout exception. To solve this, put the following lines inside the <system.web> tag of the web.config file.

Points of Interest

So, we have learned how to pull data from a database and show it in a GridView control, export data from a GridView to an Excel file, and a way of exporting huge data from a datareader and exporting that data to an Excel file.

Share

About the Author

Fuad Bin Omar is co-founder and COO of Nascenia Ltd . () Prior to joining in Nascenia he worked as a "Senior Software Engineer" at the offshore development office of Code71,Inc
Fuad have more than five years of experience in developing business applications using .NET and Ruby on Rails technologies.

My suggestion is to try the Gridview to Excel Export Tool.It's a tool for asp.net developers. It allows you to export data from sqldatasource, sqldatareader, dataview, etc. - with or without a gridview - into real Excel sheets. You can choose whether to export into xml or xlsx Excel/OpenOffice format. You can even build multisheet workbooks. you can format columns and add headers, computed columns, totals.

This error comes when you are exporting the GridView control in the Visual Studio.NET 2005 BETA Versions. I am using the released version so I never got this error. Anyway, you can solve this error but the trick is very dirty. You have to turn the eventValidation off in order for this to work.

You can do this in the web.config file but in this case the eventValidation will be turned off for all the pages.

or you can do this in the Page directive which will turn off the validation for a single page.

If you're dealing with large files you will want to use the Response object's Output property directly instead of creating a separate StringBuilder and then using ToString... Response.Output is basically already a StringBuilder.

If you would like to still use your SqlDataSource to do the updating but also set the timeout variable to something other than 30 than you can use the method from this page: click here to view solution[^]. For those that do not want to follow the link this is the important part; the SqlDataSource Selecting event exposes the command object as seen below: