Y enlazamos este repeater con una fuente de datos, en el ejemplo, un query a la base de datos AdventureWorks y a la tabla Person.Contact y llenamos el repeater
SqlConnection conn = new SqlConnection("Server=localhost;Database=AdventureWorks;Uid=sa;Pwd=");
SqlCommand cmd = new SqlCommand("SELECT top 100 Title, FirstName, MiddleName, LastName, Suffix, EmailAddress, Phone, ModifiedDate FROM Person.Contact", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
Repeater1.DataSource = ds;
Repeater1.DataBind();
protected void Button1_Click(object sender, EventArgs e) {
BindData();
ExportExcel(ds, Repeater1);
}
public static void ExportExcel(DataSet ds, Repeater RepX) {
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);
Page page = new Page();
HtmlForm form = new HtmlForm();
RepX.DataSource = ds;
RepX.DataBind();
RepX.RenderControl(htw);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=fichero.xls");
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = Encoding.Default;
HttpContext.Current.Response.Write(sb.ToString());
HttpContext.Current.Response.End();
}
}
Enlaces relacionadas:
Código del artículo
Saludos Alex.