Generar Excel desde Asp.net C# / Generate Excel from Asp.net C#

Este código lo copié de la siguiente página (Original code from link below):

http://www.buayacorp.com/archivos/exportar-el-contenido-de-un-gridview-a-excel/

Just create a page with a Gridview called GridView1 on it.
Cree una página con un Gridview llamado GridView1 en ella.

Then add a "Export to Excel" button and double clic on it, copy and paste the code below.
Luego adiciona un botón "Exportar a Excel" y dele doble clic, copie y pegue el siguiente código:

Yo adiciono las siguientes líneas para ahorrar un tiempito adicional:
I add the following lines to save time:

//added
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
//end

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);

Page page = new Page();
HtmlForm form = new HtmlForm();

GridView1.EnableViewState = false;

// Deshabilitar la validación de eventos, sólo asp.net 2
page.EnableEventValidation = false;

// Realiza las inicializaciones de la instancia de la clase Page que requieran los diseñadores RAD.
page.DesignerInitialize();

page.Controls.Add(form);
form.Controls.Add(GridView1);

page.RenderControl(htw);

Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=data.xls");
Response.Charset = "UTF-8";
Response.ContentEncoding = Encoding.Default;
Response.Write(sb.ToString());
Response.End();

Comentarios

Anónimo ha dicho que…
Gracias funciona perfecto
John H. ha dicho que…
Excelente que te haya servido. Feliz día.

Entradas populares de este blog

2da Reeleccion del presidente Alvaro Uribe?

Lo sentimos la aplicación Contactos se detuvo.

Outlook Letras inmensas al dar Responder o Reenviar