Click here to Skip to main content
Email Password   helpLost your password?

Screenshot - ExportLargeDataInExcel.jpg

Introduction

A good way to display data is to show it in a grid view. However, it becomes difficult to manipulate and filter large amounts of data in this way. Exporting data to an Excel file is a great solution for handling large amounts of data because Excel has many features -- such as sorting, searching and filtering -- that do not require you to write a single line of code. In this example, I will show:

  1. How to pull data from a database and display it in the grid.
  2. How to export data from the grid to the Excel file.
  3. How to export data from a data reader to the Excel file.
  4. How to handle large amounts of data and combat different types of errors.

Using the code

This sample uses ASP.NET 2.0, C# and SQL Server 2005. I am using a simple form of the database table to avoid unnecessary overhead. Let us assume that we have a database named UniversityManager and that 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 the ASP.NET SqlDataSource control to pull data from the database. SqlDataSource can be used as a data source that can fetch data from databases. It can be bound to an ASP.NET control. For showing this data to 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. The code at the ASP side would look like this:

<asp:GridView ID="grdStudentMarks" runat="server" 
    DataSourceID="dsStudentMarks">
    <EmptyDataTemplate>
        No Data Found
    </EmptyDataTemplate>
    <RowStyle CssClass="ClsOddRow" />
    <AlternatingRowStyle CssClass="ClsEvenRow" />
    <HeaderStyle CssClass="ClsHeaderRow" /> 
</asp:GridView>

<asp:SqlDataSource ID="dsStudentMarks" runat="server" ConnectionString=
  "Data Source=.;Initial Catalog=UniversityManager;Integrated Security=True;"
    SelectCommand="
    (
        SELECT *FROM STUDENT 
    ) 
    "> 
</asp:SqlDataSource>

<asp:Button ID="btnExportFromDatagrid" runat="server" 
    Text="Export From Grid" OnClick="btnExportFromDatagrid_Click" />

<asp:Button ID="btnExportFromDataset" runat="server" 
    Text="Export From Data set" />

When the ASP.NET page is rendered, grdStudentMarks will be populated by the data from the Student table of the UniversityManager database. Hence, Windows authentication is used. Besides this, I have taken 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 data grid to Excel. We have written this code at the Click event of btnExportFromDataGrid.

protected void btnExportFromDatagrid_Click(object sender, EventArgs e)
    {
        ExportGridToExcel(grdStudentMarks, "StudentMarks.xls");   
    }
    public void ExportGridToExcel(GridView grdGridView, string fileName)
    {
        Response.Clear();
        Response.AddHeader("content-disposition", 
            string.Format("attachment;filename={0}.xls", fileName));
        Response.Charset = "";
        Response.ContentType = "application/vnd.xls";

        StringWriter stringWrite = new StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        grdGridView.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
    }

When the button is clicked, we invoke the function ExportGridToExcel with the parameters as Gridview 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. Then with Response.ContentType we are setting an HTTP MIME Type of the output stream as application/vnd.xls. Then the RenderControl method of the GridView class is used, which outputs server control content to the provided HtmlTextWriter, htmlWrite. Finally, this is written to the Response stream.

The job is supposed to be done at this stage! However, were you to 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:

public override void VerifyRenderingInServerForm(Control control)
    {

    }

That's it! The data of the grid view will be exported to the Excel file, which should be saved to the desktop. However, there are some problems with this solution. First, if you use paging in your grid view, then only the data of an individual page will be exported instead of the data of whole grid. That means only those data which are rendered within the page will be exported. Second, if the data of the grid view is huge, you will 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 completion of the operation. So to solve this type of problem, we would use the following solution.

Timeout solution

I am going to use the SQLCommand class because by using so, 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 -- i.e. a particular column of a row -- is followed by a comma delimiter so that the CSV file can format it. The code is as follows:

protected void btnExportFromDataset_Click(object sender, EventArgs e)
{
    ExportToExcel(dsStudentMarks, "StudentMarks");
}
 
public void ExportToExcel(SqlDataSource dataSrc, string fileName)
{
    //Add Response header 

    Response.Clear();
    Response.AddHeader("content-disposition", 
        string.Format("attachment;filename={0}.csv", fileName));
    Response.Charset = "";
    Response.ContentType = "application/vnd.xls";
    //GET Data From Database                

    SqlConnection cn = new SqlConnection(dataSrc.ConnectionString);
    string query = 
        dataSrc.SelectCommand.Replace("\r\n", " ").Replace("\t", " ");
        
    SqlCommand cmd = new SqlCommand(query, cn);
        
    cmd.CommandTimeout = 999999 ;
    cmd.CommandType    = CommandType.Text;
    try
    {
        cn.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        StringBuilder sb = new StringBuilder();            
        //Add Header          

        for (int count = 0; count < dr.FieldCount; count++)
        {
            if (dr.GetName(count) != null)
                sb.Append(dr.GetName(count));
            if (count < dr.FieldCount - 1)
            {
                sb.Append(",");
            }
        }
        Response.Write(sb.ToString() + "\n");
        Response.Flush();            
        //Append Data

        while (dr.Read())
        {
            sb = new StringBuilder();
               
            for (int col = 0; col < dr.FieldCount - 1; col++)
            {
                if (!dr.IsDBNull(col))
                    sb.Append(dr.GetValue(col).ToString().Replace(",", " "));
                    sb.Append(",");
            }
            if (!dr.IsDBNull(dr.FieldCount - 1))
                sb.Append(dr.GetValue(
                dr.FieldCount - 1).ToString().Replace(",", " "));
            Response.Write(sb.ToString() + "\n");
            Response.Flush();
        }
        dr.Dispose();
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
    }
    finally
    {
        cmd.Connection.Close();
        cn.Close();
    }
    Response.End();
}

This solves the problem of downloading large amounts of data.

The problem of the SQLClient timeout exception is now solved, but there is still a possibility of getting an HtttpRequest timeout exception. To solve this problem, put the following lines inside <system.web> tag of the web.config file:

<httpRuntime maxRequestLength="209715" executionTimeout="3600" />

That's it!

Points of interest

So, we have learned how to pull data from a database and show it in the grid view control. We have learned how to export data from grid view to an Excel file, how to export huge amounts of data from the data reader and how to export that data to an Excel file. I hope that this example helps you. Feel free to give me any suggestions regarding this article. Happy coding!

History

This demo was first uploaded on June 21st, 2007.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralGreat Article Bro.
nakash2050
5:41 5 Jul '09  
You just saved my day. Was fed up of Googling for this article and I had totally forgot about "CodeProject". Thanks a lot. Big Grin
GeneralMultiple Page GridView
Frosty33
10:49 5 Jan '09  
Thank you for this code as it is very helpful and useful.

Question for you: I use a GridView with a max page dataset size of 100 columns per page. The additional pages\columns are accessible via the links at the bottom of the Gridview.

When I use your export to excel code, it appears to only export the current page worth of data.

Can I use your tool to export the entire Gridview and still keep my pagination in place?

I appreciate your help.

Frosty
GeneralRe: Multiple Page GridView
gargvijay
21:45 18 Mar '09  
I am having same issue with export (.net 3.5). Did you find any solution for this.

Thanks
GeneralRe: Multiple Page GridView
Dan Madden
3:11 24 Nov '09  
Hi gargvijay,

I don't know if you fixed it yet, but for everyone else, the way I did it was to turn OFF paging (then bind it), do my stuff, and turn paging back ON (then bind it again). Here is a little sample below ... I think I got this from MS?

GVTest.AllowPaging = false;
GVTest.DataBind();
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
HtmlForm frm = new HtmlForm();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=" + txtFile.Text + ".xls");
Response.Charset = "";
EnableViewState = false;
Controls.Add(frm);
frm.Controls.Add(GVTest);
frm.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
GVTest.AllowPaging = true;
GVTest.DataBind();

Regards,

Dan

GeneralRe: Multiple Page GridView
Dan Madden
3:12 24 Nov '09  
Hi Frosty,

see my answer to gargvijay if you still need it...

Regards,

Dan

Generalimport an Excel file
Laxmi R
1:37 5 Jan '09  
I don't have a problem exporting the datagrid as an excel file. The problem is that if the file is downloaded without Open - Save As, I have problems uploading the file back into the system. I get the error "External table is not in the expected format...". If the file is opened and Save As type Microsoft Excel Worksheet then I can upload the file w/o problems. Note that the file is saved as a MS Excel Worksheet in either case. I recall reading somewhere that there is no way around this but I need to be sure.

laxmi

GeneralHow to import an excel file which is export from gridview to excel
Laxmi R
1:34 5 Jan '09  
from a datagrid on an asp.net web page. I want users to be able to export a datagrid to an excel file, make whatever changes they need to the excel file and then import the changed excel file back into the datagrid. I have implemented this, and it works but:

1. When the user exports the datagrid to an excel file, the File Download pop up gives the choice of Open, Save or Cancel. They must first open the file and then select "File - Save As - MS Office Excel Workbook" for the excel file to be in the correct format. If they just choose Save instead of Open, the error "External table is not in the expected format..." is given when they try to import the file back in. Is there any way around this, changing some attribute or file extenstion?

2. I want to be sure that the user is in fact using the file they originally downloaded and not an excel file that they created. Is there a way of inserting hidden data like a header or something that I could check before I allow them to upload the file?

laxmi

GeneralExport Gridview in different tabs(worksheet) in excel file using c#
Umesh8738
20:05 18 Nov '08  
Hi ,
I am using asp.net 2.0 and i have 2 Grid view on form which contains data. I already export both grid 's data in single excel file but i want data should display in 2 different tabs( worksheets) for each grid.

How can i do this ?
GeneralRe: Export Gridview in different tabs(worksheet) in excel file using c#
gg4237
2:45 23 Oct '09  
You could try using GemBox.Spreadsheet .NET component.

Here is an example how easy it is to Import or Export DataGrid to Excel using GemBox.Spreadsheet.
Generalplz help me..i want to export data from datagridview to excel sheet in vb.net windows application
dilipmca04
19:43 20 Oct '08  
plz help me..i want the code to export data from datagridview to excel sheet in vb.net windows application
GeneralHow to Import CSV
adeel.xaidi
12:21 28 Aug '08  
Hi Guys,
I am having difficulty in solving an issue the scenario is as:

the table structure would be

Name nvarchar
Amount nvarccar

i have to import a csv file in asp.net2.0

which should be able to categorize the date according to the price

and please let me know that which library i have to use in order to play with a csv file

Thanks

Adeel Zaidi

QuestionStoring file in XL format
rajaron
4:00 10 Jul '08  
The file is stored in CSV format .. but want to store data XL format each data should be stored in its own cell.
In article it has used "," seprated therefore file stores in CSV any other delimeter/alternative way to store data in each cell.
AnswerRe: Storing file in XL format
ZeljkoSvedic
0:23 6 Jul '09  
Hi rajaron,

you could try GemBox .NET Excel component that is free for commercial use if you need less then 150 rows & 5 sheets.

Filip
GemBox.Spreadsheet for .NET - Easily read and write Excel (XLS, XLSX or CSV) files or export to HTML files from your .NET apps.
GeneralVery Large Results killing AppPool.
StephenHill11
12:05 26 Jun '08  
Hi,
Great Article, but I have some very large ResultSets that my users are trying to create and download, and if more than one is launched at the same time, it fills up the App Pool and brings IIS down ...

Is there a way to launch this process in it's own thread, so it doesn't fill up the App Pool and will download successfully. Or at least, if it fails, will not fill up the App Pool ???

Thanks,

Steve Hill
QuestionGreat Article!
count_rugen
12:13 18 Jun '08  
This was a terrific article my friend, but do you have any advice for those of us who use ObjectDataSource? I'm finding it very difficult to convert your large data export (using a CSV file) to use my ObjectDataSource. :-/
GeneralUse httpRunTime Element in Web.config File instead
Bhaskar Shetty
0:50 13 Aug '07  
Hello,

You can instead change httpRunTime Element in web.config and set the maxRequestLength to maximum.

You can also set the httpRuntime element for single Page also, by setting the attribute as below.







byee

Bhaskar Shetty
shettybhas@gmail.com
GeneralError
shekhar kumar das
19:40 11 Jul '07  
It's working fine. But if I make Grid View properties Allow Paging=True or Allow Sorting=True it shows Error......

RegisterForEventValidation can only be called during Render();

How can I use it with paging and sorting support.

Shekhar
GeneralRe: Error
bonhomie
14:46 30 Aug '07  
Go to the Page attributes section at the top and set the EnableEventValidation property to "false" e.g. <%@ Page Language="C#" EnableEventValidation = "false"
GeneralThanks
2 Rocks
5:32 5 Jul '07  
Brilliant, that was very helpful.

ThanksBig Grin
GeneralRe: Thanks
Fuad Bin Omar
8:52 5 Jul '07  
I am excited to know that it helped you a bit.
You are welcome Smile
GeneralWhole page comes in Excel
mehulmistry
0:58 5 Jul '07  
Hi,
I tried your example in my page, but I am getting my whole apsx page in the excel file along with the grid data?...

Am I supposed to do something else too...


GeneralRe: Whole page comes in Excel
Fuad Bin Omar
1:07 5 Jul '07  
Hello,

Please make sure that you are trying to render your gridview not the whole page.
e.g.
grdGridView.RenderControl(htmlWrite);

hence "grdGridView" is the name of your Gridview.

Please let me know whether it is resolved or not.

Thank you
GeneralRe: Whole page comes in Excel
mehulmistry
19:59 5 Jul '07  
yes I am doing exactly the same way you have done in your example. Following is the VB .NET code of the subroutine I have written.

Private Sub pvExportToExcel(ByVal grdUser As GridView, ByVal strFilename As String)
Response.Clear()
Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xls", strFilename))
Response.Charset = ""
Response.ContentType = "application/vnd.xls"

Dim stringWrite As StringWriter = New StringWriter()
Dim htmlWrite As HtmlTextWriter = New HtmlTextWriter(stringWrite)
grdUser.RenderControl(htmlWrite)
Response.Write(stringWrite.ToString())
Response.Flush()
Response.End()

End Sub

The line marked in bold is my gridview control. But I am still not getting it.


GeneralYou should use a handler
COLEMAN72
2:58 26 Jun '07  
You should put your logic for downloading (especially the Response.Write(..) portion in a handler) and render in a new target such as a new window or a frame. Refreshing the page as written will cause another download.

Regards
Coleman
GeneralRe: You should use a handler
Fuad Bin Omar
3:04 26 Jun '07  
No, there would be a single download as no code is written inside Page.Load method. You can download the code and test it Smile

Thanks


Last Updated 21 Jun 2007 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010