In this article I will explain with an example, how to export Repeater control to CSV file in ASP.Net using C# and VB.Net.


Here I am making use of Microsoft’s Northwind Database. You can download it from here.

HTML Markup

The following HTML Markup consists of:
Repeater – For displaying data.
The Repeater control consists of following templates:–
HeaderTemplate – The content of this template will not be repeated and will be placed in the top most position i.e. head section of the Repeater control.
ItemTemplate – The content of this template will be repeated for each record present in its DataSource.
ItemTemplate consists of three Label controls.
FooterTemplate – The content of this template will not be repeated and will be placed in the bottom most position i.e. footer section of the Repeater control.
Button – For exporting Repeater data to CSV file.
The Button has been assigned with an OnClick event handler.
<asp:Repeater runat="server" ID="rptCustomers">
        <table cellspacing="0" rules="all" border="1">
                <th scope="col" style="width: 80px">Customer Id</th>
                <th scope="col" style="width: 120px">Customer Name</th>
                <th scope="col" style="width: 100px">Country</th>
            <td><asp:Label ID="lblCustomerId" runat="server" Text='<%# Eval("CustomerId") %>' /></td>
            <td><asp:Label ID="lblContactName" runat="server" Text='<%# Eval("ContactName") %>' /></td>
            <td><asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>' /></td>
<br />
<asp:Button ID="btnExport" runat="server" Text="Export" OnClick="ExportToCSV" />


You will need to import the following namespaces.
using System.IO;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
Imports System.IO
Imports System.Text
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Populating Repeater control from database in ASP.Net

Inside the Page Load event handler, the Repeater control is populated with the records from the Customers table of the Northwind database.
Note: For more details on how to populate Repeater control, please refer my article Display and render Repeater control as HTML Table Layout in ASP.Net.
protected void Page_Load(object sender, EventArgs e)
    if (!this.IsPostBack)
protected void BindRepeater()
    string sql = "SELECT TOP 10 CustomerId, ContactName, Country FROM Customers";
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
        using (SqlDataAdapter sda = new SqlDataAdapter(sql, con))
            using (DataTable dt = new DataTable())
                rptCustomers.DataSource = dt;
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
    End If
End Sub
Protected Sub BindRepeater()
    Dim sql As String = "SELECT TOP 10 CustomerId, ContactName, Country FROM Customers"
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Using sda As SqlDataAdapter = New SqlDataAdapter(sql, con)
            Using dt As DataTable = New DataTable()
                rptCustomers.DataSource = dt
            End Using
        End Using
    End Using
End Sub

Exporting Repeater to CSV (Text) File

When the Export Button is clicked, the StringWriter and HtmlTextWriter class objects are created.
The StringWriter class object is passed as parameter to the HtmlTextWriter object.
A FOR EACH loop is executed over the String Array of column names and Header row is added for the CSV file.
Then, again a FOR EACH loop is executed over the items of the Repeater control i.e. Label control and a comma separated (delimited) string is generated and rows are added using the StringBuilder class.
Then, using the RenderControl method, the Repeater control has been rendered as an HTML string and the Response class properties are set.
1. Content-Disposition – It is a response header indicating, the download file is an attachment and allows setting the file name.
Note: For more details on Content-Disposition header, please refer my article What is Content Disposition Header in ASP.Net.
2. ContentType – It informs the Browser about the file type. In this case it is CSV file.
Finally, the comma separated (delimited) string is written to the Response which initiates the File download.
protected void ExportToCSV(object sender, EventArgs e)
    using (StringWriter sw = new StringWriter())
        using (HtmlTextWriter hw = new HtmlTextWriter(sw))
            StringBuilder sb = new StringBuilder();
            string[] columnNames = new string[] { "CustomerId", "ContactName", "Country" };
            foreach (string columnName in columnNames)
                //Add the Header row for CSV file.
                sb.Append(columnName + ',');
            //Add new line.
            foreach (RepeaterItem item in rptCustomers.Items)
                //Add the rows.
                sb.Append((item.FindControl("lblCustomerId") as Label).Text + ',');
                sb.Append((item.FindControl("lblContactName") as Label).Text + ',');
                sb.Append((item.FindControl("lblCountry") as Label).Text + ',');
            //Add new line.
            Response.Buffer = true;
            Response.Charset = "";
            Response.ContentType = "text/csv";
            Response.AddHeader("content-disposition", "attachment;filename=RepeaterExport.csv");
Protected Sub ExportToCSV(ByVal sender As Object, ByVal e As EventArgs)
    Using sw As StringWriter = New StringWriter()
        Using hw As HtmlTextWriter = New HtmlTextWriter(sw)
            Dim sb As StringBuilder = New StringBuilder()
            Dim columnNames As String() = New String() {"CustomerId", "ContactName", "Country"}
            For Each columnName As String In columnNames
                'Add the Header row for CSV file.
                sb.Append(columnName & ","c)
            'Add new line.
            For Each item As RepeaterItem In rptCustomers.Items
                'Add the rows.
                sb.Append((TryCast(item.FindControl("lblCustomerId"), Label)).Text + ","c)
                sb.Append((TryCast(item.FindControl("lblContactName"), Label)).Text + ","c)
                sb.Append((TryCast(item.FindControl("lblCountry"), Label)).Text + ","c)
            'Add new line.
            Response.Buffer = True
            Response.Charset = ""
            Response.ContentType = "text/csv"
            Response.AddHeader("content-disposition", "attachment;filename=RepeaterExport.csv")
        End Using
    End Using
End Sub



Export Repeater To CSV in ASP.Net

Exported CSV (Text) file

Export Repeater To CSV in ASP.Net