In this article I will explain how to export ASP.Net Repeater control to Microsoft Excel file.
HTML Markup
Below is a simple ASP.Net Repeater Control and an ASP.Net Button to export the Repeater contents to Excel.
<asp:Repeater ID="rptCustomers" runat="server">
<ItemTemplate>
<table border = "1">
<tr>
<td style = "width:100px">
<%#Eval("CustomerID") %>
</td>
<td style = "width:100px">
<%#Eval("City") %>
</td>
<td style = "width:100px">
<%#Eval("PostalCode")%>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
<br />
<asp:Button ID="btnExport" runat="server" Text="Export" OnClick = "ExportToExcel" />
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Data;
VB
Imports System.IO
Imports System.Data
Export To Excel
On the click of the Export button the following event handler is executed which exports the ASP.Net Repeater contents to Excel.
C#
protected void ExportToExcel(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=RepeaterExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
rptCustomers.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
VB
Protected Sub ExportToExcel(sender As Object, e As EventArgs)
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=RepeaterExport.xls")
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
rptCustomers.RenderControl(hw)
Response.Output.Write(sw.ToString())
Response.Flush()
Response.End()
End Sub
No comments:
Post a Comment