Tutoriales gratuitos para el aprendizaje de la programacion informatica! Recuerda que si lo puedes imaginar... lo puedes programar!

Exportar GRID a HTML

Crear proyecto:



En el form1 agregar:
  • 1 DataGridView
  • 1 Button



Crear la conexion para llenar el DataGridView:

'ver tutorial de conexion->  Conexión con sql desde .net

Imports System.ComponentModel
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class FORM1
    Public CONEXION As NewOleDbConnection("PROVIDER=SQLOLEDB;"&
                 "DATA SOURCE=NOMBRE DEL SERVIDOR;" &
                 "INITIAL CATALOG=BASE DE DATOS;" &
                 "USER ID=USUARIO;PASSWORD=CLAVE")
    Dim SQL As String
    Public ORDEN_BD As OleDb.OleDbCommand
    Private D_TABLE As DataTable
    Private D_ADAPTER As OleDbDataAdapter
    Sub CONSULTA()
        CONEXION.Open()
        SQL = "SELECT * FROM TABLA ORDER BY CAMPO"
        ORDEN_BD = New OleDb.OleDbCommand(SQL, CONEXION)
        ORDEN_BD.CommandType = CommandType.Text
        ORDEN_BD.ExecuteNonQuery()
        REM CIERRO LA CONEXION
        D_ADAPTER = New OleDbDataAdapter(ORDEN_BD)
        D_TABLE = New DataTable
        D_ADAPTER.Fill(D_TABLE)
        DataGridView1.DataSource = D_TABLE
        CONEXION.Close()
    End Sub

    'llamamos la consulta para llenar el grid
    Private Sub FORM1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Call CONSULTA()
    End Sub

    Sub ExportarHTML()
        Try
            'Intentar generar el documento.
            Dim titulos As New ArrayList()
            Dim datostabla As New DataTable()
            'Path que guarda el reporte en el escritorio de windows (Desktop).
            Dim [OF] As New HTML(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\Reporte.html")
            'Se obtienen los titulos del DataGridView y se crean las columnas de la tabla.
            For Each item As DataGridViewColumn In DataGridView1.Columns()
                titulos.Add(item.HeaderText)
                datostabla.Columns.Add()
            Next
            'Se crean las filas de la tabla.
            For Each item As DataGridViewRow In DataGridView1.Rows
                Dim rowx As DataRow = datostabla.NewRow()
                datostabla.Rows.Add(rowx)
            Next
            'Se pasan los datos del dataGridView a la tabla.
            For Each item As DataGridViewColumn In DataGridView1.Columns
                For Each itemx As DataGridViewRow In DataGridView1.Rows
                    datostabla.Rows(itemx.Index)(item.Index) = DataGridView1(item.Index, itemx.Index).Value
                Next
            Next
            [OF].ExportarDatosHTML(titulos, datostabla)
            Process.Start([OF].xpath)
        Catch ex As Exception
            'Si el intento es fallido, mostrar MsgBox.
            MessageBox.Show("No se puede generar el documento HTML.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Call ExportarHTML()
    End Sub
End Class


Crear la clase: Con el nombre de HTML




Copiar el siguiente codigo en la clase:

Imports System.IO
Imports System.Text
Public Class HTML
    Private w As StreamWriter
    Private ruta As String
    Public Property xpath() As String
        Get
            Return ruta
        End Get
        Set(ByVal value As String)
            value = ruta
        End Set
    End Property
    'Constructor que establece el path del archivo.
    Public Sub New(ByVal path As String)
        ruta = path
    End Sub
    'Exporta datos a un archivo HTML.
    Public Sub ExportarDatosHTML(ByVal titulos As ArrayList, ByVal datos As DataTable)
        Try
            Dim fs As New FileStream(ruta, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)
            w = New StreamWriter(fs)
            Dim comillas As String = Char.ConvertFromUtf32(34)
            Dim html As New StringBuilder()
            html.Append("<!DOCTYPE html PUBLIC" & comillas & "-//W3C//DTD XHTML 1.0 Transitional//EN" & comillas & " " & comillas & "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" & comillas & ">")
            html.Append("<html xmlns=" & comillas & "http://www.w3.org/1999/xhtml" & comillas & ">")
            html.Append("<head>")
            html.Append("<meta http-equiv=" & comillas & "Content-Type" & comillas & "content=" & comillas & "text/html;charset=utf-8" & comillas & "/>")
            html.Append("<title>Reporte </title>")
            html.Append("</head>")
            html.Append("<body>")
            html.Append("<p><font face=" & comillas & "Tahoma" & comillas & "size=" & comillas & "6" & comillas & ">" + "Reporte de Registros" + "</font></p>")
            html.Append("<p><font face=" & comillas & "Tahoma" & comillas & "size=" & comillas & "3" & comillas & ">" + "Reporte para la fecha: " + Now.Date() + "</font></p>")
            html.Append("</br>")
            html.Append("<table CELLSPACING=0 CELLPADDING=5 border=2 BORDERCOLOR=" & comillas & "#000000" & comillas & " bgcolor=" & comillas & "#FFFFFF" & comillas & ">")
            html.Append("<tr> <b>")
            For Each item As Object In titulos
                html.Append("<th>" & "<font face=" & comillas & "Tahoma" & comillas & "size=" & comillas & "2" & comillas & ">" & item.ToString() & "</font></th>")
            Next
            html.Append("</b> </tr>")
            'Generando datos desde el DataGridView.     
            For i As Integer = 0 To datos.Rows.Count - 1
                html.Append("<tr>")
                For j As Integer = 0 To datos.Columns.Count - 1
                    html.Append("<td>" & "<font face=" & comillas & "Tahoma" & comillas & "size=" & comillas & "2" & comillas & ">" + datos.Rows(i)(j).ToString() & "</font></td>")
                Next
                html.Append("</tr>")
            Next
            html.Append("</body>")
            html.Append("</html>")
            w.Write(html.ToString())
            w.Close()
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
End Class

Resultados:





No hay comentarios:

Publicar un comentario