Anda di halaman 1dari 9

Agregar Referencias de word excel y pdf

Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.OleDb
Imports System.IO
Public Class JheysonMatta_Excel_txt
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.Even
tArgs) Handles MyBase.Load
Dim da As New SqlDataAdapter
Dim cmd As New SqlCommand
Dim cn As New SqlConnection("Data Source=.;Initial Catalog=Northwind;Int
egrated Security=True")
Dim dt As New DataTable
With cmd
.CommandType = CommandType.Text
.CommandText = "SELECT CustomerID, CompanyName,ContactTitle,Address,
City,Region,PostalCode FROM Customers"
.Connection = cn
End With
da.SelectCommand = cmd
da.Fill(dt)
DataGridView1.DataSource = dt
End Sub
Function GridAExcel(ByVal ElGrid As DataGridView) As Boolean
'Creamos las variables
Dim exApp As New Microsoft.Office.Interop.Excel.Application
Dim exLibro As Microsoft.Office.Interop.Excel.Workbook
Dim exHoja As Microsoft.Office.Interop.Excel.Worksheet
Try
'Aadimos el Libro al programa, y la hoja al libro
exLibro = exApp.Workbooks.Add
exHoja = exLibro.Worksheets.Add()
' Cuantas columnas y cuantas filas?
Dim NCol As Integer = ElGrid.ColumnCount
Dim NRow As Integer = ElGrid.RowCount
'Aqui recorremos todas las filas, y por cada fila todas las columnas
y vamos escribiendo.
For i As Integer = 1 To NCol
exHoja.Cells.Item(1, i) = ElGrid.Columns(i - 1).Name.ToString
'exHoja.Cells.Item(1, i).HorizontalAlignment = 3
Next
For Fila As Integer = 0 To NRow - 1
For Col As Integer = 0 To NCol - 1
exHoja.Cells.Item(Fila + 2, Col + 1) = ElGrid.Rows(Fila).Cel
ls(Col).Value
Next
Next
'Titulo en negrita, Alineado al centro y que el tamao de la columna s
e ajuste al texto
exHoja.Rows.Item(1).Font.Bold = 1
exHoja.Rows.Item(1).HorizontalAlignment = 3
exHoja.Columns.AutoFit()
'Aplicacin visible
exApp.Application.Visible = True
exHoja = Nothing
exLibro = Nothing
exApp = Nothing
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error al exportar a Excel"
)
Return False
End Try
Return True
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.E
ventArgs) Handles Button1.Click
Call GridAExcel(DataGridView1)
End Sub
--------------------------------------------------------------------------------
-----------------------------------------
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button6.Clic
k
' GENERANDO ALGUNAS VARIABLES UTILES
If File.Exists("C:\Users\Jheyson Matta\Desktop\Registro.txt") Then
File.Delete("C:\Users\Jheyson Matta\Desktop\ARCHIVO.txt")
End If
Const Dat As String = ("C:\Users\Jheyson Matta\Desktop\Registro.txt")
' GERENANDO EL ARCHIVO
Using f As New IO.StreamWriter(Dat, True)
' AGREGANDO LAS COLUMNAS
Dim col As String = ""
' AGREGANDO LAS FILAS
Dim row As String = ""
Dim i As Integer = 0
For Each r As DataGridViewRow In DataGridView1.Rows
For Each c As DataGridViewColumn In DataGridView1.Columns
row = row & "'" & Convert.ToString(r.Cells(c.HeaderText).Val
ue) & "' "
Next
If i < DataGridView1.Rows.Count - 1 Then row &= Environment.NewL
ine
Next
'AGREGANDO LA INFORMACION
f.WriteLine(row)
End Using
End Sub
End Class
--------------------------------------------------------------------------------
-----------------------------
Imports PdfSharp
Imports PdfSharp.Pdf
Imports PdfSharp.Drawing
Imports PdfSharp.Drawing.Layout
Public Class JheysonMatta_PDF
Private maTamao() As Integer
Private miTamao As Integer = 0
Private miPaginas As Integer = 0
Private miPaginaActual As Integer
Private Sub Form3_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
Me.DataGridView1.AllowUserToAddRows = False
Dim msCadenaSQL As String = "Data Source=.;Initial Catalog=Northwind;Int
egrated Security=True"
Try
' Configuramos una conexin con el origen de datos.
Using loConexion As New SqlConnection(msCadenaSQL)
' crear adaptadores
Dim lDataAdapter As New SqlDataAdapter("SELECT CustomerID, Compa
nyName,ContactTitle,Address,City,Region,PostalCode FROM Customers", loConexion)
Dim lDataTable As New DataTable
lDataAdapter.Fill(lDataTable)
Me.DataGridView1.DataSource = lDataTable
ReDim maTamao(Me.DataGridView1.ColumnCount - 1)
For liCiclo As Integer = 0 To Me.DataGridView1.ColumnCount - 1
maTamao(liCiclo) = Me.DataGridView1.Columns(liCiclo).Width
miTamao += Me.DataGridView1.Columns(liCiclo).Width
Next
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub lP_ImprimirDGV(ByRef roDGV As DataGridView)
Dim ldSaltoLinea As Double
' Crea el documento Pdf
Dim Documento As PdfDocument = New PdfDocument
' Crea un objeto pagina
Dim Pagina As PdfPage
' Aade una pagina vacia
Pagina = Documento.AddPage
Pagina.Size = PageSize.A4
' Crea un Objeto XGraphics
Dim Grafico As XGraphics
' Asigna un Objeto XGraphics a la pagina
Grafico = XGraphics.FromPdfPage(Pagina)
' Crea un Objeto LapizPDF
Dim miBoli As New LapizPDF(Grafico)
' Crea la fuente
Dim FuenteLinea As XFont = New XFont("Courier New", 10, XFontStyle.Regul
ar)
Dim FuenteCabecera As XFont = New XFont("Bradley Hand ITC", 12, XFontSty
le.Bold)
ldSaltoLinea = FuenteLinea.GetHeight(Grafico)
Dim Archivo As String = Directory.GetCurrentDirectory() & "\Prueba.pdf"
Dim liLinea As Integer = 0
Dim liAncho As Integer
Dim liAlto As Integer
Dim liAltomodulo As Integer = 50
Dim liNumLineas As Integer
Dim miPaginaActual As Integer = 0
If miTamao > 570 Then
Pagina.Orientation = PageOrientation.Landscape
liAncho = 820
liAlto = 575
Else
Pagina.Orientation = PageOrientation.Portrait
liAncho = 575
liAlto = 820
End If
liNumLineas = CInt(((liAlto - (liAltomodulo * 3)) / CInt(ldSaltoLinea))
- 3)
If Me.DataGridView1.RowCount Mod liNumLineas = 0 Then
miPaginas = Me.DataGridView1.RowCount \ liNumLineas
Else
miPaginas = (Me.DataGridView1.RowCount \ liNumLineas) + 1
End If
miPaginaActual += 1
Dim miDgv As New DGVImpreso(Grafico, CInt(ldSaltoLinea), 30, 30, liAncho
, liAlto, liAltomodulo, maTamao)
'IMPRIMIR LA CABECERA
miDgv.Cabecera(Me.DataGridView1, miBoli, FuenteCabecera, "LISTADO DE PRU
EBA")
liLinea = 0
'recorrer todo el datagrid
For Each loFila As DataGridViewRow In roDGV.Rows
If liLinea = liNumLineas Then
miDgv.Pie(miBoli, FuenteCabecera, miPaginaActual, miPaginas)
liLinea = 0
' Aade una pagina vacia
Pagina = Documento.AddPage
Pagina.Size = PageSize.A4
If miTamao > 570 Then
Pagina.Orientation = PageOrientation.Landscape
Else
Pagina.Orientation = PageOrientation.Portrait
End If
' Asigna un Objeto XGraphics a la pagina
Grafico = XGraphics.FromPdfPage(Pagina)
' Asigna un Objeto LapizPDF al Grafico
miBoli = New LapizPDF(Grafico)
miDgv = New DGVImpreso(Grafico, CInt(ldSaltoLinea), 30, 30, liAn
cho, liAlto, liAltomodulo, maTamao)
miPaginaActual += 1
'IMPRIMIR LA CABECERA
miDgv.Cabecera(Me.DataGridView1, miBoli, FuenteCabecera, "LISTAD
O DE PRUEBA")
End If
'Imprimir Linea
miDgv.Linea(loFila, miBoli, FuenteLinea)
liLinea += 1
Next
miDgv.Pie(miBoli, FuenteCabecera, miPaginaActual, miPaginas)
Try
'si el archivo esta abierto da error, para que averiguen como saber
si el archivo esta abierto y cerrarlo antes de grabar uno nuevo
Documento.Save(Archivo)
Process.Start(Archivo)
Catch ex As Exception
MessageBox.Show(ex.Message, "lP_Imprimir", MessageBoxButtons.OKCance
l, MessageBoxIcon.Information)
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.
Click
lP_ImprimirDGV(Me.DataGridView1)
End Sub
End Class
Public Class LapizPDF
Private mGrafico As XGraphics
Public Property Grafico() As XGraphics
Get
Return mGrafico
End Get
Set(ByVal Value As XGraphics)
mGrafico = Value
End Set
End Property
Public Sub New(ByVal objGrafico As XGraphics)
mGrafico = objGrafico
End Sub
Public Sub CuadroRedondo(ByVal PosX As Integer, ByVal PosY As Integer, ByVal
Ancho As Integer, ByVal Alto As Integer, ByVal Grosor As Integer, Optional ByVa
l Sombra As Boolean = False)
Dim Cuadro As XRect = New XRect(PosX, PosY, Ancho, Alto)
Dim Lapiz As XPen = New XPen(XColor.FromArgb(0, 0, 0), Grosor)
Dim Elipse As XSize
Elipse.Height = 10
Elipse.Width = 10
If Sombra = True Then
mGrafico.DrawRoundedRectangle(Lapiz, XBrushes.Beige, Cuadro, Elipse)
Else
mGrafico.DrawRoundedRectangle(Lapiz, Cuadro, Elipse)
End If
End Sub
Public Sub CuadroRecto(ByVal PosX As Integer, ByVal PosY As Integer, ByVal A
ncho As Integer, ByVal Alto As Integer, ByVal Grosor As Integer, Optional ByVal
Sombra As Boolean = False)
Dim Cuadro As XRect = New XRect(PosX, PosY, Ancho, Alto)
Dim Lapiz As XPen = New XPen(XColor.FromArgb(0, 0, 0), Grosor)
If Sombra = True Then
mGrafico.DrawRectangle(Lapiz, XBrushes.Beige, Cuadro)
Else
mGrafico.DrawRectangle(Lapiz, Cuadro)
End If
End Sub
Public Sub LineaH(ByVal PosX1 As Integer, ByVal PosY1 As Integer, ByVal Anch
o As Integer, ByVal Grosor As Integer)
Dim Lapiz As XPen = New XPen(XColor.FromArgb(0, 0, 0), Grosor)
Dim Punto1 As New Point(PosX1, PosY1)
Dim Punto2 As New Point(PosX1 + Ancho, PosY1)
mGrafico.DrawLine(Lapiz, Punto1, Punto2)
End Sub
Public Sub LineaV(ByVal PosX1 As Integer, ByVal PosY1 As Integer, ByVal Alto
As Integer, ByVal Grosor As Integer)
Dim Lapiz As XPen = New XPen(XColor.FromArgb(0, 0, 0), Grosor)
Dim Punto1 As New Point(PosX1, PosY1)
Dim Punto2 As New Point(PosX1, PosY1 + Alto)
mGrafico.DrawLine(Lapiz, Punto1, Punto2)
End Sub
Public Sub Texto(ByVal lsTexto As String, ByVal Fuente As XFont, ByVal brush
As XBrush, ByVal PosX As Integer, ByVal PosY As Integer)
mGrafico.DrawString(lsTexto, Fuente, brush, PosX, PosY)
End Sub
Public Sub Imagen(ByVal Imagen As XImage, ByVal PosX As Integer, ByVal PosY
As Integer, ByVal Ancho As Integer, ByVal Alto As Integer)
mGrafico.DrawImage(Imagen, PosX, PosY, Ancho, Alto)
End Sub
Public Sub TextoFormateado(ByVal lsTexto As String, ByVal Fuente As XFont, B
yVal brush As XBrush, ByVal PosX As Integer, ByVal PosY As Integer, ByVal Ancho
As Integer, ByVal Alto As Integer, ByVal Alinear As Integer)
Dim Formateador As XTextFormatter ' Objeto para formatear texto
Dim Rect As New XRect(PosX, PosY, Ancho, Alto)
Formateador = New XTextFormatter(Grafico)
Formateador.Alignment = CType(Alinear, XParagraphAlignment)
Formateador.DrawString(lsTexto, Fuente, brush, Rect)
End Sub
End Class
Public Class DGVImpreso
Private mGrafico As XGraphics
Private mSaltoLinea As Double
Private mPosX As Integer
Private mPosY As Integer
Private mAncho As Integer
Private mAlto As Integer
Private mAltoModulo As Integer
Private maTamao() As Integer
Private Const cPosXIni As Integer = 10
Private Const cPosYIni As Integer = 10
Public Sub New(ByVal vGrafico As XGraphics, ByVal vSaltoLinea As Integer, By
Val vPosX As Integer, ByVal vPosY As Integer, ByVal vAncho As Integer, ByVal vAl
to As Integer, ByVal vAltoModulo As Integer, ByRef raTamao() As Integer)
mGrafico = vGrafico
mSaltoLinea = vSaltoLinea
mPosX = vPosX
mPosY = vPosY
mAncho = vAncho
mAlto = vAlto
mAltoModulo = vAltoModulo
maTamao = raTamao
End Sub
Public Sub Cabecera(ByRef DGV As DataGridView, ByRef Boli As LapizPDF, ByVal
vFuente As XFont, ByVal vTexto As String)
Boli.CuadroRedondo(cPosXIni, cPosYIni, mAncho, mAlto, 3)
Boli.CuadroRedondo(cPosXIni, cPosYIni, mAncho, mAltoModulo * 2, 0, True)
Boli.TextoFormateado(vTexto, vFuente, XBrushes.Black, 10, CInt(mAltoModu
lo / 2), mAncho, 10, XParagraphAlignment.Center)
Boli.TextoFormateado("Fecha: " & CStr(Date.Today), vFuente, XBrushes.Bla
ck, 10, CInt(mAltoModulo / 2), (mAncho - cPosXIni), cPosXIni, XParagraphAlignmen
t.Right)
Boli.LineaH(cPosXIni, mAltoModulo + cPosYIni, mAncho, 1)
mPosX = 30
mPosY = mAltoModulo + 40
'Dim liLineaV As Integer = 0
For liCiclo As Integer = 0 To DGV.ColumnCount - 1
Boli.Texto(vbNullString & DGV.Columns(liCiclo).Name, vFuente, XBrush
es.Black, mPosX, mPosY)
If liCiclo < DGV.ColumnCount - 1 Then
mPosX += maTamao(liCiclo)
'liLineaV += 1
'If liLineaV <= mColVisibles Then
Boli.LineaV((mPosX - 5), mAltoModulo + cPosYIni, mAlto + cPosYIn
i - (mAltoModulo * 2), 1)
'End If
End If
Next
mPosY = CInt((mAltoModulo * 2) + (mSaltoLinea * 3))
End Sub
Public Sub Linea(ByRef Fila As DataGridViewRow, ByRef Boli As LapizPDF, ByVa
l vFuente As XFont)
mPosX = 30
For liCiclo As Integer = 0 To Fila.Cells.Count - 1
'If Fila.Cells(liCiclo).Visible = True Then
Boli.Texto(vbNullString & Fila.Cells(liCiclo).Value.ToString, vFuent
e, XBrushes.Black, mPosX, mPosY)
If liCiclo < Fila.Cells.Count - 1 Then
mPosX += maTamao(liCiclo)
End If
'End If
Next
mPosY += CInt(mSaltoLinea)
End Sub
Public Sub Pie(ByRef Boli As LapizPDF, ByVal vFuente As XFont, ByVal vPagina
As Integer, ByVal vPaginas As Integer)
mPosX = 20
mPosY = CInt(mAlto - mAltoModulo) + cPosYIni
Boli.LineaH(10, mPosY, mAncho, 1)
Boli.CuadroRedondo(cPosXIni, mPosY, mAncho, mAltoModulo, 0, True)
Boli.TextoFormateado("Pie de pagina", vFuente, XBrushes.Black, mPosX, mP
osY + 20, (mAncho - 2 * mPosX), mAltoModulo, XParagraphAlignment.Left)
Boli.TextoFormateado("Pagina: " & CStr(vPagina) & " de " & vPaginas, vFu
ente, XBrushes.Black, mPosX, mPosY + 20, (mAncho - mPosX), mAltoModulo, XParagra
phAlignment.Right)
End Sub
End Class
--------------------------------------------------------------------------------
-----------------------------------------------
Imports System.Data
Imports System.Data.SqlClient
Imports Microsoft.Office.Interop.Word
Public Class JheysonMatta_Word
Dim StrCn = "Data Source=.;Initial Catalog=Northwind;Integrated Security=Tru
e"
Dim Cn As New SqlConnection(StrCn)
Dim Da As New SqlDataAdapter
Dim Cmd As New SqlCommand
Dim Dt As DataTable
Private Sub Form_Load(ByVal sender As System.Object, ByVal e As System.Event
Args) Handles MyBase.Load
With Cmd
.CommandType = CommandType.Text
.CommandText = "SELECT CustomerID, CompanyName,ContactTitle,Address,
City,Region,PostalCode FROM Customers"
.Connection = Cn
End With
Da.SelectCommand = Cmd
Dt = New DataTable
Da.Fill(Dt)
DataGridView1.DataSource = Dt
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.E
ventArgs) Handles Button1.Click
Call GrillaAWord(DataGridView1)
End Sub
Public Function GrillaAWord(ByVal Grilla As DataGridView)
Dim Word As Application
Dim Doc As Document
Dim Table As Table
Dim Rng As Range
Dim Prf1 As Paragraph
Dim Prf2 As Paragraph
Dim Prf3 As Paragraph
Word = CreateObject("Word.Application")
Word.Visible = False
Doc = Word.Documents.Add
Prf1 = Doc.Content.Paragraphs.Add
Prf1.Range.Text = "Jheyson Matta - Exportando DataGridView1 a Word"
Prf1.Range.Font.Color = WdColor.wdColorBlue
Prf1.Range.Font.Bold = True
Prf1.Format.SpaceAfter = 24
Prf1.Range.InsertParagraphAfter()
Prf2 = Doc.Content.Paragraphs.Add(Doc.Bookmarks.Item("\endofdoc").Range)
Prf2.Range.Text = "DESCRIPCION"
Prf2.Range.Font.Color = WdColor.wdColorBlack
Prf2.Format.SpaceAfter = 6
Prf2.Range.InsertParagraphAfter()
Prf3 = Doc.Content.Paragraphs.Add(Doc.Bookmarks.Item("\endofdoc").Range)
Prf3.Range.Text = "Programa hecho a pedido de Suscriptores de mi canal."
& _
" Suscribete: https://www.youtube.com/user/jheysonmatta:"
Prf3.Range.Font.Bold = False
Prf3.Format.SpaceAfter = 24
Prf3.Range.InsertParagraphAfter()
Dim NCol As Integer = Grilla.ColumnCount
Dim NRow As Integer = Grilla.RowCount
'alternativo
ProgressBar1.Maximum = NRow - 1
Table = Doc.Tables.Add(Doc.Bookmarks.Item("\endofdoc").Range, Grilla.Row
Count, Grilla.ColumnCount)
'Agregando Los Campos De La Grilla
For i As Integer = 1 To NCol
Table.Cell(1, i).Range.Text = Grilla.Columns(i - 1).Name.ToString
Next
'Agregando Los Registros A La Tabla
For Fila As Integer = 0 To NRow - 2
For Col As Integer = 0 To NCol - 1
If Grilla.Rows(Fila).Cells(Col).Value IsNot DBNull.Value Then
Table.Cell(Fila + 2, Col + 1).Range.Text = Grilla.Rows(Fila)
.Cells(Col).Value
End If
Next
'Incremento
ProgressBar1.Increment(1)
Next
'Negrita y Kursiva Para Los Nombres De Los Campos
Table.Rows.Item(1).Range.Font.Bold = True
Table.Rows.Item(1).Range.Font.Italic = True
'Boder De La Tabla
Table.Borders.InsideLineStyle = WdLineStyle.wdLineStyleDot
Table.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleDot
Table.Borders.InsideColor = WdColor.wdColorBlue
Rng = Doc.Bookmarks.Item("\endofdoc").Range
Rng.InsertParagraphAfter()
Rng.InsertAfter("ATTE: Jheyson Matta Per.")
MessageBox.Show("Exportacion Completado.. ")
Word.Visible = True
End Function
End Class

Anda mungkin juga menyukai