Importacion de excel a visual basic (codigo)
Option Explicit On
Option Strict On
Public Class Form1
Private Sub Form1_Load( _
ByVal sender As System.Object, _
ByVal e AsSystem.EventArgs) Handles MyBase.Load
Button1.Text = "Cargar"
txtRange.Text = "A1:C15"
End Sub
Private Sub Button1_Click( _
ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button1.Click
' // Pasar valores para Leer el rango
loadRange("c:\book1.xls", "sheet1", txtRange.Text, DataGridView1)
EndSub
' ----------------------------------------------------------------------------------
' // Subrutina para conectar al libro Excel y obtener el rango de datos
'----------------------------------------------------------------------------------
Private Sub loadRange( _
ByVal sFileName As String, _
ByVal sSheetName As String, _
ByVal sRange AsString, _
ByVal dv As DataGridView)
Try
' // Comprobar que el archivo Excel existe
If System.IO.File.Exists(sFileName) Then
Dim objDataSet AsSystem.Data.DataSet
Dim objDataAdapter As System.Data.OleDb.OleDbDataAdapter
' // Declarar la Cadena de conexión
Dim sCs As String ="provider=Microsoft.Jet.OLEDB.4.0; " & "data source=" & sFileName & "; Extended Properties=Excel 8.0;"
Dim objOleConnection As System.Data.OleDb.OleDbConnection
objOleConnection =New System.Data.OleDb.OleDbConnection(sCs)
' // Declarar la consulta SQL que indica el libro y el rango de la hoja
Dim sSql As String = "select * from " & "[" &sSheetName & "$" & sRange & "]"
' // Obtener los datos
objDataAdapter = New System.Data.OleDb.OleDbDataAdapter(sSql, objOleConnection)
' // Crear...
Regístrate para leer el documento completo.