La Web del Programador: Comunidad de Programadores
 
    Pregunta:  55753 - LEER DATOS DE EXCEL DESDE VB.NET
Autor:  Juan Gomez
Hola a todos, tengo una excel que tengo que cargar con una aplicacion .NET

Leo los datos

El problema viene cuando hay en excel hay una columna de datos numericos mezclados con textos, no se que hace excel que al volcar los datos al dataset me recoge nulos en aquellas columnas donde predomina el valor numerico sobre el texto, es decir, si tengo una columna con 9 filas de numeros y en una pongo un texto, me vuelca un un nulo en ese valor. A la inversa tambien ocurre

¿A que se debe?

¿Que funcion debo poner en el SELECT para que me lo traiga todo? gracias

  Respuesta:  rickcode
Espero te ayude Juan Gomez

Option Explicit On
Option Strict On

Public Class Form1
Private Sub Form1_Load( _
ByVal sender As System.Object, _
ByVal e As System.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:ook1.xls", "sheet1", txtRange.Text, DataGridView1)

End Sub

' ----------------------------------------------------------------------------------
' // 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 As String, _
ByVal dv As DataGridView)

Try
' // Comprobar que el archivo Excel existe
If System.IO.File.Exists(sFileName) Then

Dim objDataSet As System.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 DataSet y llenarlo
objDataSet = New System.Data.DataSet

objDataAdapter.Fill(objDataSet)
' // Cerrar la conexión
objOleConnection.Close()

' // Enlazar DataGrid al Dataset
With dv
.DataSource = objDataSet
.DataMember = objDataSet.Tables(0).TableName
End With
Else
MsgBox("No se ha encontrado el archivo: " & sFileName, MsgBoxStyle.Exclamation)
End If

Exit Sub
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try

End Sub
End Class