Pasar un ASP.NET Repeater/DataSet a Excel.

Vamos hacer el proceso completo. Ponemos un control repeater y un botón en la página aspx, el ejemplo completo esta al final del artículo.

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();

Ejecutando esto en el navegador veremos el listado y si pulsamos el boton para crear el excel pondremos en el evento del botón el siguiente código:

protected void Button1_Click(object sender, EventArgs e) {
  BindData();
  ExportExcel(ds, Repeater1);
}

La función ExportExcel es la que creara el Excel a partir de un dataset y un repeater:


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();
}
}

Y esto lanzara un Excel para poder guardarlo o visualizarlo.

Saludos
Alex.

Enlaces relacionadas:

Código del artículo 

Comenta el artículo