I'm working on an application that need to read info from a Excel-file. The file is distributed to a number of clients where the application should run. I can´t affect the file before distribution. If the sheet I want to read is named Sheet1 everything is fine but if the sheet is named Sheet 1 i got problem.
The workbook name is picked from My.Settings. and the sheetname is in a variable SheetName by using GetOleDbSchemaTable earlier in the code.
If the Sheetname contains a space stSql contains
"SELECT DISTINCT T1, T2, T3 FROM ['Sheet 1$'C:E]"
If not stSql contains
"SELECT DISTINCT T1, T2, T3 FROM [Sheet1$C:E]"
When the sheetname includes a space it is between ' ' so i don´t understand why it is not working.
My other problem is that the file don´t have column headers. This code assumes column headers. If I want all columns a "SELECT * FROM.. will work without headers but hear i need a SELECT DISTINCT.. so i need to include a hint of which columns I want to read.
I have tried "SELECT DISTINCT [C],[D],[E] FROM [" & SheetName& "C:E]" but then I get "No Value Given For
One OR More required Parameters"
Any hints how to solve these problems.
The workbook name is picked from My.Settings. and the sheetname is in a variable SheetName by using GetOleDbSchemaTable earlier in the code.
If the Sheetname contains a space stSql contains
"SELECT DISTINCT T1, T2, T3 FROM ['Sheet 1$'C:E]"
If not stSql contains
"SELECT DISTINCT T1, T2, T3 FROM [Sheet1$C:E]"
When the sheetname includes a space it is between ' ' so i don´t understand why it is not working.
My other problem is that the file don´t have column headers. This code assumes column headers. If I want all columns a "SELECT * FROM.. will work without headers but hear i need a SELECT DISTINCT.. so i need to include a hint of which columns I want to read.
I have tried "SELECT DISTINCT [C],[D],[E] FROM [" & SheetName& "C:E]" but then I get "No Value Given For
One OR More required Parameters"
Any hints how to solve these problems.
Code:
Try
Dim j As Integer
Dim stSQL As String = "SELECT DISTINCT T1, T2, T3 FROM [" & SheetName& "C:E]"
Dim cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & My.Settings.Source_Sortfil & ";Extended Properties=""Excel 8.0;HDR=YES"";")
Dim cmd As New OleDbCommand(stSQL, cn)
cn.Open()
Dim dr As OleDbDataReader = _
cmd.ExecuteReader(CommandBehavior.CloseConnection)
j = 0 'counter for arrayindex
While dr.Read()
List_Etikettext(j, 0) = dr(0)
List_Etikettext(j, 1) = dr(1)
If IsDBNull(dr(2)) Then
List_Etikettext(j, 2) = ""
Else
List_Etikettext(j, 2) = dr(2)
End If
j = j + 1
End While
dr.Close()
cmd.Dispose()
cn.Dispose()
Catch ex As Exception
MsgBox(ex.Message)
End Try