PDA

Ver la versión completa : Crear Reportes de una Base de Datos en Excel




Shell Root
10-15-2009, 09:11 PM
[VB.Net] Crear Reportes de una Base de Datos en Excel



CONTENIDO


Como Agregar la Referencia (http://comunidad.dragonjar.org/f175/crear-reportes-de-una-base-de-datos-en-excel-8498/#post19774)
Codigo (http://comunidad.dragonjar.org/f175/crear-reportes-de-una-base-de-datos-en-excel-8498/#post19775)
Explicación del Codigo (http://comunidad.dragonjar.org/f175/crear-reportes-de-una-base-de-datos-en-excel-8498/#post19776)





INTRODUCCIÓN


A muchos desarrolladores se les a presentado la necesidad de crear reportes con ciertos estilos provenientes de herramientas de terceros, por lo regular los ejecutivos les gusta la forma en que se presentan los informes en formato EXCEL y muchas veces informes generados por sistemas de gestión, se nos solicita que sean exportados a EXCEL para ajustarlos a sus necesidades y gustos.

Bueno con este articulo pretendo mostrarle una forma sencilla de leer una base de datos y generar un informe directamente en EXCEL aprovechando todas las funcionalidades de esta herramienta, se podría decir que mas del 50 porciento de las computadoras de oficina cuentan con alguna versión de Microsoft Office, así que estimo que le será de utilidad alguno de ustedes.


Sacado del ElGuille.info

Shell Root
10-15-2009, 09:12 PM
Como Agregar la Referencia

Creamos una nueva solución en Visual Studio .NET y agregamos una referencia a la librería de objeto de Excel que se encuentra en la paleta COM de la ventana de agregar referencias en Visual Studio .NET

http://img9.imageshack.us/img9/2403/elmorenoref.th.jpg (http://img9.imageshack.us/my.php?image=elmorenoref.jpg)

Si la versión de Office con la que cuentan es 2000 la librería seria Microsoft Excel 9.0 Object Library, luego hacemos clic en Select y luego en OK y listo.


Sacado del ElGuille.info

Shell Root
10-15-2009, 09:19 PM
Codigo


Primero creamos la conexión a la base de datos SQL Server 2000


Creamos una Clase = Conexion.vb


Imports System.Data.SqlClient

Public Class conexion
'Variables
Public build As New SqlConnectionStringBuilder
Public cnn As New SqlConnection(build.ConnectionString)

Public Sub conexion()
build = New SqlConnectionStringBuilder
With build
.DataSource = "(Local)"
.InitialCatalog = "Northwind"
.IntegratedSecurity = True
End With
cnn = New SqlConnection(build.ConnectionString)
Try
cnn.Open()
Catch ex As Exception
MsgBox("Error: " & ex.Message, MsgBoxStyle.Critical)
liberarTodo()
Exit Sub
End Try
End Sub

Public Sub liberarTodo()
cnn.Close()
End Sub
End Class

Segundo En el WebForm Ponemos el siguiente codigo

Imports Microsoft.Office.Interop
Imports System.Data.SqlClient

Partial Class _Default
Inherits System.Web.UI.Page
Dim vconexion As New Conexion

Dim m_Excel As Excel.Application
Dim CategoryName As String 'Variable para controlar la ruptura por nombre de categorías
Dim objLibroExcel As Excel.Workbook 'Creamos un objeto WorkBook
Dim objHojaExcel As Excel.Worksheet 'Creamos un objeto WorkSheet
Dim objDataSet As New Data.DataSet("ExcelTest")
Dim i As Integer = 5

Protected Sub BtnCrear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnCrear.Click
vconexion.conexion()

Dim objSQLAdapter As New SqlDataAdapter("SELECT CategoryName,ProductID,ProductName,UnitPrice FROM Products,Categories WHERE Products.CategoryID = Categories.CategoryID ORDER BY Categories.CategoryID", vconexion.cnn)
Dim objDataSet As New Data.DataSet("ExcelTest")

objSQLAdapter.Fill(objDataSet, "Categories")

m_Excel = New Excel.Application
m_Excel.Visible = True

objLibroExcel = m_Excel.Workbooks.Add()
objHojaExcel = objLibroExcel.Worksheets(1)
objHojaExcel.Visible = Excel.XlSheetVisibility.xlSheetVisible

objHojaExcel.Activate()

objHojaExcel.Range("A1:G1").Merge()
objHojaExcel.Range("A1:G1").Value = "Ejemplo de Como Hacer Reportes de Excel en VB.NET"
objHojaExcel.Range("A1:G1").Font.Bold = True
objHojaExcel.Range("A1:G1").Font.Size = 15

objHojaExcel.Range("A2:D2").Merge()
objHojaExcel.Range("A2:D2").Value = "By:alex19910218"
objHojaExcel.Range("A2:D2").Font.Italic = True
objHojaExcel.Range("A2:D2").Font.Size = 13

objHojaExcel.Range("A4").Value = "Categoría"
objHojaExcel.Range("A4").Font.Bold = True
objHojaExcel.Range("A4").Font.Size = 12

objHojaExcel.Range("B4").Value = "Código"
objHojaExcel.Range("B4").Font.Bold = True
objHojaExcel.Range("B4").Font.Size = 12

objHojaExcel.Range("C4").Value = "Nombre"
objHojaExcel.Range("C4").Font.Bold = True
objHojaExcel.Range("C4").Font.Size = 12

objHojaExcel.Range("D4").Value = "Precio RD$"
objHojaExcel.Range("D4").Font.Bold = True
objHojaExcel.Range("D4").Font.Size = 12

CategoryName = ""

For Each objRow As Data.DataRow In objDataSet.Tables(0).Rows
CategoryName = objRow.Item(0)

objHojaExcel.Cells(i, "A") = objRow.Item(0) 'CategoryName'
objHojaExcel.Cells(i, "B") = objRow.Item(1) 'ProductID'
objHojaExcel.Cells(i, "C") = objRow.Item(2) 'ProductName'
objHojaExcel.Cells(i, "D") = objRow.Item(3) 'UnitPrice'

i += 1
Next
End Sub
End Class


Sacado del ElGuille.info

Shell Root
10-15-2009, 09:20 PM
Explicación del Codigo

Libreria Para Trabajar con Excel

Imports Microsoft.Office.InteropLibreria Para Trabajar con Bases de Datos SQL

Imports System.Data.SqlClientClase Conexion

Dim vconexion As New ConexionCreamos un objeto Excel

Dim m_Excel As Excel.ApplicationVariable para controlar la ruptura por nombre de categorías

Dim CategoryName As StringCreamos un objeto WorkBook

Dim objLibroExcel As Excel.WorkbookCreamos un objeto WorkSheet

Dim objHojaExcel As Excel.Worksheet
Dim objDataSet As New Data.DataSet("ExcelTest")Fila (Posiciones Celdas)

Dim i As Integer = 5Abrimos la conexion

vconexion.conexion()Ejecutamos la Consulta SQL + la Conexión

Dim objSQLAdapter As New SqlDataAdapter("SELECT CategoryName,ProductID,ProductName,UnitPrice FROM Products,Categories WHERE Products.CategoryID = Categories.CategoryID ORDER BY Categories.CategoryID", vconexion.cnn)Filtramos la Datos el DataSet

objSQLAdapter.Fill(objDataSet, "Categories")Iniciamos una instancia a Excel

m_Excel = New Excel.Application
m_Excel.Visible = TrueCreamos una instancia del Workbooks de Excel

objLibroExcel = m_Excel.Workbooks.Add()Creamos una instancia de la primera hoja de trabajo de Excel

objHojaExcel = objLibroExcel.Worksheets(1)
objHojaExcel.Visible = Excel.XlSheetVisibility.xlSheetVisibleHacemos esta hoja la visible en pantalla (como seleccionamos la primera esto no es necesario si seleccionamos una diferente a la primera si lo necesitaríamos).

objHojaExcel.Activate()Crear el encabezado de nuestro informe

objHojaExcel.Range("A1:G1").Merge()
objHojaExcel.Range("A1:G1").Value = "Ejemplo de Como Hacer Reportes de Excel en VB.NET"
objHojaExcel.Range("A1:G1").Font.Bold = True
objHojaExcel.Range("A1:G1").Font.Size = 15Crear el subencabezado de nuestro informe

objHojaExcel.Range("A2:D2").Merge()
objHojaExcel.Range("A2:D2").Value = "By:alex19910218"
objHojaExcel.Range("A2:D2").Font.Italic = True
objHojaExcel.Range("A2:D2").Font.Size = 13Agregamos la Columna Categoria

objHojaExcel.Range("A4").Value = "Categoría"
objHojaExcel.Range("A4").Font.Bold = True
objHojaExcel.Range("A4").Font.Size = 12Agregamos la Columna Codigo

objHojaExcel.Range("B4").Value = "Código"
objHojaExcel.Range("B4").Font.Bold = True
objHojaExcel.Range("B4").Font.Size = 12Agregamos la Columna Nombre

objHojaExcel.Range("C4").Value = "Nombre"
objHojaExcel.Range("C4").Font.Bold = True
objHojaExcel.Range("C4").Font.Size = 12Agregamos la Columna 'Precio RD$'

objHojaExcel.Range("D4").Value = "Precio RD$"
objHojaExcel.Range("D4").Font.Bold = True
objHojaExcel.Range("D4").Font.Size = 12Vaciamos la variable

CategoryName = ""Asignar la categoría impresa

CategoryName = objRow.Item(0)Asignar los valores de los registros a las celdas

objHojaExcel.Cells(i, "A") = objRow.Item(0) 'CategoryName'
objHojaExcel.Cells(i, "B") = objRow.Item(1) 'ProductID'
objHojaExcel.Cells(i, "C") = objRow.Item(2) 'ProductName'
objHojaExcel.Cells(i, "D") = objRow.Item(3) 'UnitPrice'Avanzamos una fila

i += 1