Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Export Data from Repeater/Datagrid to Excel

5.00/5 (4 votes)
12 May 2014CPOL1 min read 18K  
Export data from Repeater/Datagrid to Excel

Introduction

This tip will give you a summary of how to export data from a Repeater to Excel sheet. One can very well use the same to import the same from Datagrid.

Background

You need to have basic knowledge of creating and binding a repeater / datagrid.

Using the Code

Place a button on the web page from which the user is just click away to download the data to Excel sheet.

Your aspx code will be like below.

Specify an OnClick function for the button. Specify a name to your OnClick event.

In this case, it is Excel_Click.

NOTE: The OnClick function will trigger when the user clicks on the below button.

ASP.NET
<asp:Button ID="btnExporttoExcel" runat="server" Text="Export to Excel" OnClick="Excel_Click"/>  

You now need to define the above event in your code behind file.

For the below code, instead of Repeater2, specify your Repeater ID.

Please note here in order to write the data from repeater to Excel, the Repeater needs to be in visible mode.

The code will look like below:

C#
protected void Excel_Click(object sender, EventArgs e)
      {
          {
              Response.ClearContent();
              Response.Buffer = true;
              Response.AddHeader("content-disposition", "attachment;filename=Details.xls");
              Response.Charset = "";
              Response.ContentType = "application/excel";
              System.IO.StringWriter sw = new System.IO.StringWriter();
              HtmlTextWriter htm = new HtmlTextWriter(sw);
              Repeater2.RenderControl(htm);
              Response.Write(sw.ToString());
              Response.End();
          }
      }

Your data is now ready to be downloaded in an Excel sheet.

Happy coding! :)

Points of Interest

In case the repeater you are trying to bind is in Invisible mode, then on the button click, make it visible and at the end of the code, set the visibility to false. You can use the same for Datagrid as well.

History

  • 12th May, 2014: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)