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.
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.
OnClick function for the button. Specify a name to your
In this case, it is
OnClick function will trigger when the user clicks on the below button.
<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:
protected void Excel_Click(object sender, EventArgs e)
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htm = new HtmlTextWriter(sw);
Your data is now ready to be downloaded in an Excel sheet.
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.
12th May, 2014: Initial post