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.
Database
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">
<HeaderTemplate>
<table cellspacing="0" rules="all" border="1">
<tr>
<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>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<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>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<br />
<asp:Button ID="btnExport" runat="server" Text="Export" OnClick="ExportToCSV" />
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
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.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindRepeater();
}
}
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())
{
sda.Fill(dt);
rptCustomers.DataSource = dt;
rptCustomers.DataBind();
}
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindRepeater()
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()
sda.Fill(dt)
rptCustomers.DataSource = dt
rptCustomers.DataBind()
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.
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.
C#
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.
sb.Append("\r\n");
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 + ',');
sb.Append("\r\n");
}
//Add new line.
sb.Append("\r\n");
rptCustomers.RenderControl(hw);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment;filename=RepeaterExport.csv");
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
}
}
VB.Net
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)
Next
'Add new line.
sb.Append(vbCrLf)
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)
sb.Append(vbCrLf)
Next
'Add new line.
sb.Append(vbCrLf)
rptCustomers.RenderControl(hw)
Response.Clear()
Response.Buffer = True
Response.Charset = ""
Response.ContentType = "text/csv"
Response.AddHeader("content-disposition", "attachment;filename=RepeaterExport.csv")
Response.Output.Write(sb.ToString())
Response.Flush()
Response.End()
End Using
End Using
End Sub
Screenshots
Repeater
Exported CSV (Text) file
Downloads