Libreria:: 'Exportamos Los Caracteres de Las Columnas

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Libreria:

Imports System.Data.OleDb

Public Class Form1

Public Sub Exportar_Excel(ByVal dgv As DataGridView, ByVal pth As String)

Dim xlApp As Object = CreateObject("Excel.Application")

'crear una nueva hoja de calculo

Dim xlWB As Object = xlApp.WorkBooks.add

Dim xlWS As Object = xlWB.WorkSheets(1)

'exportamos los caracteres de las columnas

For c As Integer = 0 To EMPLEADOSDataGridView.Columns.Count - 1

xlWS.cells(1, c + 1).value = EMPLEADOSDataGridView.Columns(c).HeaderText

Next

'exportamos las cabeceras de columnas

For r As Integer = 0 To EMPLEADOSDataGridView.RowCount - 1

For c As Integer = 0 To EMPLEADOSDataGridView.Columns.Count - 1

xlWS.cells(r + 2, c + 1).value = EMPLEADOSDataGridView.Item(c, r).Value

Next

Next

'guardamos la hoja de calculo en la ruta especificada

xlWB.saveas(pth)

xlWS = Nothing

xlWB = Nothing

xlApp.quit()

xlApp = Nothing
End Sub

Private Sub GenerarEXCEL_Click(sender As Object, e As EventArgs) Handles


GenerarEXCEL.Click

Dim save As New SaveFileDialog

save.Filter = "Archivo Excel | *.xlsx"

If save.ShowDialog = Windows.Forms.DialogResult.OK Then

Exportar_Excel(EMPLEADOSDataGridView, save.FileName)

End If

End Sub

Codigo de boton

Private Sub Button1_Click(sender As Object, e As EventArgs)

Dim stRuta As String = ""

Dim openFD As New OpenFileDialog

With openFD

.Title = "Seleccionar archivos"

.Filter = "Archivos Excel(*.xls;*.xlsx)|*.xls;*xlsx|Todos los archivos(*.*)|*.*"

.Multiselect = False

.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.Desktop

If .ShowDialog = Windows.Forms.DialogResult.OK Then

stRuta = .FileName

End If

End With

Try

Dim stConexion As String = ("Provider=Microsoft.ACE.OLEDB.12.0;" & ("Data Source=" &


(stRuta & ";Extended Properties=""Excel 12.0;Xml;HDR=YES;IMEX=2"";")))

Dim cnConex As New OleDbConnection(stConexion)


Dim Cmd As New OleDbCommand("Select * From [Hoja1$]")

Dim Ds As New DataSet

Dim Da As New OleDbDataAdapter

Dim Dt As New DataTable

cnConex.Open()

Cmd.Connection = cnConex

Da.SelectCommand = Cmd

Da.Fill(Ds)

Dt = Ds.Tables(0)

Me.EMPLEADOSDataGridView.DataSource = Dt

Catch ex As Exception

MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")

End Try

End Sub

End Class

You might also like