Foros del Web » Programación para mayores de 30 ;) » .NET »

[SOLUCIONADO] Leer datos de excel desde vb.net

Estas en el tema de Leer datos de excel desde vb.net en el foro de .NET en Foros del Web. Hola, necesito leer los datos que hay en un excel desde vb.net. Ya he echo la conexión y abro el xls pero no se como ...
  #1 (permalink)  
Antiguo 03/05/2013, 01:38
 
Fecha de Ingreso: abril-2012
Mensajes: 449
Antigüedad: 12 años
Puntos: 7
Leer datos de excel desde vb.net

Hola, necesito leer los datos que hay en un excel desde vb.net. Ya he echo la conexión y abro el xls pero no se como coger los datos. Os pongo el código para que me echéis una mano.

Código vb.net:
Ver original
  1. Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
  2.         Dim xls_cn As New OleDbConnection
  3.         Dim xls_cmd As New OleDbCommand
  4.         Dim xls_reader As New OleDbDataAdapter
  5.         Dim mysql_conn As New MySqlConnection
  6.         Dim mysql_comando As New MySqlCommand
  7.         Dim xls_sql, mysql_connstring, insert As String
  8.  
  9.         If Me.servidor.Text = "" Or Me.usuario.Text = "" Or Me.password.Text = "" Or Me.bbdd.Text = "" Then
  10.             MsgBox("Completa datos de conexión")
  11.             Exit Sub
  12.         End If
  13.  
  14.         Try
  15.             If xlsx = "" Then
  16.  
  17.                 MsgBox("Selecciona un archivo.")
  18.                 Exit Sub
  19.             Else
  20.  
  21.                 Dim strExtension As String = ""
  22.                 Dim nombreXls As String
  23.                 Dim m_Excel As Microsoft.Office.Interop.Excel.Application
  24.  
  25.                 nombreXls = Path.GetFileName(xlsx)
  26.                 strExtension = Path.GetExtension(xlsx)
  27.                 If strExtension = ".xls" Or strExtension = ".xlsx" Then
  28.                     'MsgBox("es un archivo excel")
  29.                     If (File.Exists(xlsx)) Then
  30.                         xls_cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + xlsx + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=0'"
  31.                         'xls_cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.12.0;Data Source=" + xlsx + ";Extended Properties='Excel 12.0;HDR=YES'"
  32.                         Using xls_cn
  33.  
  34.                             m_Excel = CreateObject("Excel.Application")
  35.                             m_Excel.Workbooks.Open(xlsx)
  36.                             xls_cn.Open()
  37.                             xls_cmd.CommandText = "SELECT * FROM [Hoja1$]"
  38.                             xls_cmd.Connection = xls_cn
  39.                             xls_reader.SelectCommand = xls_cmd
  40.                            
  41.  
  42.                             [B]'quiero aquí obtener los datos del excel ya que algunos de ellos luego tengo que guardarlos en una base de datos[/B]
  43.  
  44.                         End Using
  45.  
  46.                         'Eliminamos la instancia de Excel de memoria
  47.                         If Not m_Excel Is Nothing Then
  48.  
  49.                             m_Excel.Quit()
  50.                             m_Excel = Nothing
  51.                         End If
  52.                     End If
  53.                 Else
  54.  
  55.                     MsgBox("Introduzca un archivo .xls o .xlsx .")
  56.                     Exit Sub
  57.                 End If
  58.             End If
  59.  
  60.         Catch ex As Exception
  61.             MsgBox("Error" & Chr(13) & Chr(13) & ex.Message)
  62.         End Try
  63.     End Sub

__________________
Gracias por todo;

Un saludo
  #2 (permalink)  
Antiguo 04/05/2013, 08:12
 
Fecha de Ingreso: marzo-2011
Mensajes: 36
Antigüedad: 13 años
Puntos: 1
Respuesta: Leer datos de excel desde vb.net

Bueno yo uso la dll EPPlus me funciona muy bien, te anexo mi codigo para que puedas realizar lo que tu necesitas

Dim NewFile As FileInfo = New FileInfo(Server.MapPath("uploaded.xlsx"))
Dim NewTemplate = New FileInfo(Server.MapPath("uploaded.xlsx"))
Dim XlPackage = New ExcelPackage(NewFile, NewTemplate)
Dim sheetDatos = XlPackage.Workbook.Worksheets(Me.TxtHoja.Text)

If sheetDatos IsNot Nothing Then

Dim Termine As Boolean = False
Dim Fila As Integer = 9

While Not Termine

archivo = sheetDatos.Cells("C" & Fila).Value

Try
If archivo IsNot Nothing Then

If Fila = 9 Then
Dim Fecha As Date = sheetDatos.Cells("P" & Fila).Value
Query.BorrarMesalSubir(Fecha.Month, Fecha.Year)
End If

row = tabla.NewRow

row.Item = sheetDatos.Cells("A" & Fila).Value
row.Planta = sheetDatos.Cells("B" & Fila).Value

tabla.Rows.Add(row)
adapt.Update(tabla)

Else
Termine = True
End If

Fila = Fila + 1

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

End If


Catch ex As Exception

End Try
  #3 (permalink)  
Antiguo 06/05/2013, 06:55
 
Fecha de Ingreso: abril-2012
Mensajes: 449
Antigüedad: 12 años
Puntos: 7
Respuesta: Leer datos de excel desde vb.net

Cita:
Iniciado por josemanuel31675 Ver Mensaje
Bueno yo uso la dll EPPlus me funciona muy bien, te anexo mi codigo para que puedas realizar lo que tu necesitas

Dim NewFile As FileInfo = New FileInfo(Server.MapPath("uploaded.xlsx"))
Dim NewTemplate = New FileInfo(Server.MapPath("uploaded.xlsx"))
Dim XlPackage = New ExcelPackage(NewFile, NewTemplate)
Dim sheetDatos = XlPackage.Workbook.Worksheets(Me.TxtHoja.Text)

If sheetDatos IsNot Nothing Then

Dim Termine As Boolean = False
Dim Fila As Integer = 9

While Not Termine

archivo = sheetDatos.Cells("C" & Fila).Value

Try
If archivo IsNot Nothing Then

If Fila = 9 Then
Dim Fecha As Date = sheetDatos.Cells("P" & Fila).Value
Query.BorrarMesalSubir(Fecha.Month, Fecha.Year)
End If

row = tabla.NewRow

row.Item = sheetDatos.Cells("A" & Fila).Value
row.Planta = sheetDatos.Cells("B" & Fila).Value

tabla.Rows.Add(row)
adapt.Update(tabla)

Else
Termine = True
End If

Fila = Fila + 1

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

End If


Catch ex As Exception

End Try
Hola,
No entiendo muy bien como lo haces.
¿No se podría hacer como lo estoy haciendo yo? ¿Alguien me puede echar una mano?
__________________
Gracias por todo;

Un saludo
  #4 (permalink)  
Antiguo 06/05/2013, 19:24
Avatar de emmax  
Fecha de Ingreso: agosto-2010
Ubicación: Sonora
Mensajes: 172
Antigüedad: 13 años, 7 meses
Puntos: 8
Respuesta: Leer datos de excel desde vb.net

Con el codigo que ya tienes puedes hacer un OleDbDataAdapter y llenar un DataTable con el y ya despues una opcion seria llenar un DataGridView para ver los datos....
  #5 (permalink)  
Antiguo 07/05/2013, 01:53
 
Fecha de Ingreso: abril-2012
Mensajes: 449
Antigüedad: 12 años
Puntos: 7
Respuesta: Leer datos de excel desde vb.net

Cita:
Iniciado por emmax Ver Mensaje
Con el codigo que ya tienes puedes hacer un OleDbDataAdapter y llenar un DataTable con el y ya despues una opcion seria llenar un DataGridView para ver los datos....
Esto es lo que me has comentado?? He echo lo siguiente pero me tarda muchisimo para llegar a leer una fila cada vez.

Código vb.net:
Ver original
  1. 'obtener el nombre del archivo
  2.                 nombreXls = Path.GetFileName(xlsx)
  3.                 'obtener la extension del archivo
  4.                 strExtension = Path.GetExtension(xlsx)
  5.                 If strExtension = ".xls" Or strExtension = ".xlsx" Then
  6.                     'MsgBox("es un archivo excel")
  7.                     If (File.Exists(xlsx)) Then
  8.                         xls_cn = New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + xlsx + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=0'")
  9.                         'xls_cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + xlsx + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=0'"
  10.                         'xls_cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.12.0;Data Source=" + xlsx + ";Extended Properties='Excel 12.0;HDR=YES'"
  11.                         m_Excel = CreateObject("Excel.Application")
  12.                         m_Excel.Workbooks.Open(xlsx)
  13.  
  14.                         Dim dt As New DataTable("Datos")
  15.  
  16.                         Using xls_cn
  17.  
  18.                             xls_cn.Open()
  19.                             xls_cmd.CommandText = "SELECT * FROM [Hoja1$]"
  20.                             xls_cmd.Connection = xls_cn
  21.                             xls_reader.SelectCommand = xls_cmd
  22.  
  23.                             'contar candidad de filas del excel
  24.                             total = m_Excel.Range("a1").CurrentRegion.Rows.Count
  25.  
  26.                             For i = 0 To total - 2
  27.                                 'Guardamos los datos en el DataTable
  28.                                 Dim da As New OleDbDataAdapter(xls_cmd)
  29.                                 da.Fill(dt)
  30.  
  31.                                 fecha = dt.Rows(i).Item(2)
  32.                                 factura = dt.Rows(i).Item(3)
  33.                                 telefono = dt.Rows(i).Item(4).ToString
  34.                                 extension = dt.Rows(i).Item(5).ToString
  35.                                 tTrafico = dt.Rows(i).Item(6)
  36.                                 cantidad = dt.Rows(i).Item(8)
  37.                                 bruto = dt.Rows(i).Item(10)
  38.                                 neto = dt.Rows(i).Item(13)
  39.                                 facturado = dt.Rows(i).Item(16)
  40.                             Next
  41.                             MsgBox("valor de i: " + i)
  42.                         End Using
  43.                     End If
  44.                 Else
  45.  
  46.                     MsgBox("Introduzca un archivo .xls o .xlsx .")
  47.                     Exit Sub
  48.                 End If

Porque puede ser? estoy haciendo algo mal?
__________________
Gracias por todo;

Un saludo
  #6 (permalink)  
Antiguo 07/05/2013, 02:06
 
Fecha de Ingreso: abril-2012
Mensajes: 449
Antigüedad: 12 años
Puntos: 7
Respuesta: Leer datos de excel desde vb.net

Me respondo a mi misma. Eso me pasa por que tengo que sacar lo siguiente fuera del for.

Código vb.net:
Ver original
  1. 'Guardamos los datos en el DataTable
  2. Dim da As New OleDbDataAdapter(xls_cmd)
  3. da.Fill(dt)

No me había dado cuenta.
__________________
Gracias por todo;

Un saludo
  #7 (permalink)  
Antiguo 21/07/2015, 16:16
 
Fecha de Ingreso: julio-2015
Ubicación: Rosario
Mensajes: 1
Antigüedad: 8 años, 8 meses
Puntos: 0
Respuesta: Leer datos de excel desde vb.net

Estimada maialenlopez,
entiendo que ha transcurrido bastante tiempo, pero necesito su ayuda. He cargado este código y no funciona correctamente, tarda demasiado tiempo en ejecutarse. Quizás no he copiado bien el code a pesar que lo he revisado.
Agradeceré me ayudes con esto.

saludos

Etiquetas: bd, excel, net, sql, vb
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 02:11.