En este mini-post explico cómo es posible exportar un control GridView(El cuál en html se traduce al tag <table></table>).

1 – Tenemos la siguiente ASPX:


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ExportGridView.aspx.cs" Inherits="testsl.Web.ExportGridView" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
        </asp:GridView>
    </div>
    <asp:Button ID="Button1" runat="server" Text="Exportar" 
        onclick="Button1_Click" />
    </form>
</body>
</html>

2 – En pantalla se verá de la siguiente forma:

3 -El code-behind queda de la siguiente forma. Allí el método ExportToExcel permite hacer lo correspondiente a generar un archivo tipo .xls . Observece la clase Person, va a ser el tipo de datos de la colección List que va a servir de fuente de datos para el objeto GridView.

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.UI.HtmlControls;
using System.Text;

namespace testsl.Web
{
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Pais { get; set; }
    }
    public partial class ExportGridView : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                List<Person> personas = new List<Person>();
                personas.Add(new Person { Id = 1, Name = "Jose", Pais = "Uruguay" });
                personas.Add(new Person { Id = 2, Name = "Pedro", Pais = "Venezuela" });
                personas.Add(new Person { Id = 3, Name = "Antonio", Pais = "Chile" });
                personas.Add(new Person { Id = 4, Name = "Mario", Pais = "Ecuador" });
                personas.Add(new Person { Id = 5, Name = "Juan", Pais = "México" });
                personas.Add(new Person { Id = 6, Name = "Felipe", Pais = "Colombia" });
                GridView1.DataSource = personas;
                GridView1.DataBind();
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            ExportToExcel("Informe.xls", GridView1);
        }

        private  void ExportToExcel(string nameReport, GridView wControl)
        {
            HttpResponse response = Response;
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            Page pageToRender = new Page();
            HtmlForm form = new HtmlForm();
            form.Controls.Add(wControl);
            pageToRender.Controls.Add(form);
            response.Clear();
            response.Buffer = true;
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment;filename=" + nameReport);
            response.Charset = "UTF-8";
            response.ContentEncoding = Encoding.Default;
            pageToRender.RenderControl(htw);
            response.Write(sw.ToString());
            response.End();
        }
    }
   
}

VB


Imports System.IO

Public Class GridViewToExcel
    Inherits System.Web.UI.Page

    Private Sub GridViewToExcel_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim personas As New List(Of Person)()
            personas.Add(New Person() With { _
             .Id = 1, _
             .Name = "Jose", _
             .Pais = "Uruguay" _
            })
            personas.Add(New Person() With { _
             .Id = 2, _
             .Name = "Pedro", _
             .Pais = "Venezuela" _
            })
            personas.Add(New Person() With { _
             .Id = 3, _
             .Name = "Antonio", _
             .Pais = "Chile" _
            })
            personas.Add(New Person() With { _
             .Id = 4, _
             .Name = "Mario", _
             .Pais = "Ecuador" _
            })
            personas.Add(New Person() With { _
             .Id = 5, _
             .Name = "Juan", _
             .Pais = "México" _
            })
            personas.Add(New Person() With { _
             .Id = 6, _
             .Name = "Felipe", _
             .Pais = "Colombia" _
            })
            GridView1.DataSource = personas
            GridView1.DataBind()
        End If
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
        ExportToExcel("Informe.xls", GridView1)
    End Sub

    Private Sub ExportToExcel(ByVal nameReport As String, ByVal wControl As GridView)
        Dim responsePage As HttpResponse = Response
        Dim sw As New StringWriter()
        Dim htw As New HtmlTextWriter(sw)
        Dim pageToRender As New Page()
        Dim form As New HtmlForm()
        form.Controls.Add(wControl)
        pageToRender.Controls.Add(form)
        responsePage.Clear()
        responsePage.Buffer = True
        responsePage.ContentType = "application/vnd.ms-excel"
        responsePage.AddHeader("Content-Disposition", "attachment;filename=" & nameReport)
        responsePage.Charset = "UTF-8"
        responsePage.ContentEncoding = Encoding.Default
        pageToRender.RenderControl(htw)
        responsePage.Write(sw.ToString())
        responsePage.End()
    End Sub

   
End Class

Public Class Person

    Private _id As Integer
    Public Property Id() As Integer
        Get
            Return _id
        End Get
        Set(ByVal value As Integer)
            _id = value
        End Set
    End Property

    Private _name As String
    Public Property Name() As String
        Get
            Return _name
        End Get
        Set(ByVal value As String)
            _name = value
        End Set
    End Property

    Private _pais As String
    Public Property Pais() As String
        Get
            Return _pais
        End Get
        Set(ByVal value As String)
            _pais = value
        End Set
    End Property

End Class

Como se vé básicamente el método permite generar un response embebiendo el codigo html hacia el cliente con el contentType application/vnd.ms-excel esto y a través de definir la extensión como .xls permite generar un archivo de tipo excel , el cual si lo abrimos quedará se la siguiente forma.

Anuncios