Question

I have an excel on a shared drive and my application is using an Oledb connection to read data from the excel into a DataGridView.

    cn = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;" + "data source=" + skuPath + ";Extended Properties=""Excel 12.0;HDR=YES;""")
    q1 = "select * from [" + year + "$B4:AM300]"
    da = New System.Data.OleDb.OleDbDataAdapter(q1, cn)

    Try
        cn.Open()
        da.Fill(ds, "Table1")
    Catch e As OleDb.OleDbException
        Dim errorMsg As String
        Dim i As Integer
        errorMsg = ""
        For i = 0 To e.Errors.Count - 1
            errorMsg += "Index #" & i.ToString() & ControlChars.Cr _
                           & "Message: " & e.Errors(i).Message & ControlChars.Cr _
                           & "NativeError: " & e.Errors(i).NativeError & ControlChars.Cr _
                           & "Source: " & e.Errors(i).Source & ControlChars.Cr _
                           & "SQLState: " & e.Errors(i).SQLState & ControlChars.Cr
        Next i
    End Try

    cn.Close()
    dt = ds.Tables(0)

When the excel file is already open by another user you get this notification in excel: enter image description here

And in those situations my code returns this error on the last line:

An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll
Additional information: Cannot find table 0.

So i understand is that because the file is in use then the entire connection returns nothing and data table is therefore empty. I found a few way of determining if a file is in use or not but nothing regarding how to read from a file in use. Is it possible? and if so how?

Please remember i only need to read the file and if its possible to always open it as a readonly that would awesome!

Was it helpful?

Solution

You can't. You have to close the open file before read it even if you use the ODBC(read only). Ref: http://forums.asp.net/t/1083489.aspx?open+a+Microsoft+Jet+OLEDB+4+0+connection+to+excel+file+read+only

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top