Excel - einzelne Zelle auslesen per OLEDB Verbindung

  • VB.NET

Es gibt 1 Antwort in diesem Thema. Der letzte Beitrag () ist von kinobi.

    Excel - einzelne Zelle auslesen per OLEDB Verbindung

    Hallo

    ich brauch mal wieder etwas Hilfe. Ich möchte eine einzelne Zelle aus einer Excel-Datei auslesen ohne sie in Excel zu öffnen.

    VB.NET-Quellcode

    1. .
    2. .
    3. .
    4. oConn.Open()
    5. Dim cmd As OleDbCommand
    6. cmd = New OleDbCommand("SELECT * FROM [" & excelsheet & "$" & "A3:A3" & "]", oConn)
    7. GetExcelCellValue = Nothing
    8. Dim reader As OleDbDataReader = cmd.ExecuteReader
    9. While reader.Read()
    10. GetExcelCellValue = reader(0)
    11. End While
    12. reader.Close()
    13. oConn.Close()


    Leider gibt er mir für die Zelle A3 nothing zurück. Wenn ich anstatt A3:A3, A2:A3 schreibe, dann bekomme ich den in Inhalt aus A3 zurück. Kann mir wer sagen wo der Fehler liegt?

    Vielen Dank
    Dirk
    Hab es selber gelöst. Der Fehler lag im ConnectionString. Dort hatte ich für HDR=YES eingetragen...das kommt vom ständigen copy&paste :)

    hier die komplette Funktion

    VB.NET-Quellcode

    1. Public Function GetExcelCellValue(ByVal excelfile As String, ByVal excelsheet As String, ByVal cell As String) As String
    2. If File.Exists(excelfile) = False Then Return Nothing
    3. Dim FileInfo As FileInfo = New FileInfo(excelfile)
    4. Dim DT As New DataTable
    5. Dim oConn As OleDbConnection = New OleDbConnection
    6. If excelfile.Contains(".xlsx") Then
    7. oConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
    8. "Data Source=" & excelfile & ";" & _
    9. "Extended Properties=""Excel 12.0 Xml;HDR=No"";"
    10. ElseIf excelfile.Contains(".xls") Then
    11. oConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    12. "Data Source=" & excelfile & ";" & _
    13. "Extended Properties=""Excel 8.0;HDR=No;IMEX=1"";"
    14. Else
    15. Return Nothing
    16. Exit Function
    17. End If
    18. oConn.Open()
    19. Dim cmd As OleDbCommand
    20. cmd = New OleDbCommand("SELECT * FROM [" & excelsheet & "$" & cell & ":" & cell & "]", oConn)
    21. GetExcelCellValue = Nothing
    22. Try
    23. Dim reader As OleDbDataReader = cmd.ExecuteReader '(CommandBehavior.SchemaOnly)
    24. '' Get the data itself.
    25. While reader.Read()
    26. GetExcelCellValue = reader(0)
    27. End While
    28. reader.Close()
    29. oConn.Close()
    30. Catch ex As Exception
    31. End Try
    32. End Function


    die Variable "cell" ist mit "A1" oder "C12" usw. anzugeben.

    Gruß
    Dirk