Why the excel file not opening using this code? error occurs - vb.net

ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source='" + fileName + "'; Extended Properties=Excel 5.0"
Dim ExcelConnection As System.Data.OleDb.OleDbConnection
ExcelConnection = New System.Data.OleDb.OleDbConnection(ConnectionString)
ExcelQuery = "Select * from [Sheet2$]"
Dim ExcelCommand As New System.Data.OleDb.OleDbCommand(ExcelQuery, ExcelConnection)
ExcelConnection.Open()
Dim ExcelReader As System.Data.OleDb.OleDbDataReader
ExcelReader = ExcelCommand.ExecuteReader()
While (ExcelReader.Read)
End While
ExcelConnection.Close()
ExcelReader.Close()
Error occurs on line
ExcelConnection.Open()
External table is not in the expected format.
PLease help
Thank you

Use
public static string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=Excel 12.0;";
as your connection string. Find more information here: Excel "External table is not in the expected format.".

Related

Create table from Excel file

I'm trying to create a temp table on my database from an Excel file uploaded by the user. I cannot understand where is the problem and why Visual Studio is throwing that exception.
Code
Private Sub Excel_Load(ByVal filePath As String)
Dim myConn As SqlConnection
Dim myCmd As SqlCommand
Dim sqlCmd As String
Dim filename As String = Path.GetFileNameWithoutExtension(filePath)
'Setting up Connection'
myConn = New SqlConnection("Server=*****;Database=*****;User ID=*****;Password=*****;Integrated Security=SSPI;")
myConn.Open()
'Create table'
sqlCmd = "CREATE TABLE XlsTemp AS (SELECT * FROM EXCELLINK [" & filename & "$])"
'Execute Query'
myCmd = myConn.CreateCommand()
myCmd.CommandText = sqlCmd
myCmd.ExecuteNonQuery()
myConn.Close()
End Sub
Exception
SqlException: The object name 'EXCELLINK' is not valid.
Peu_UNRAE is my Excel file.
At the end I come up with this solution:
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim fileExcelType As String
//Get the file extension in order to use the propper provider
If IO.Path.GetExtension(fileExcel.ToUpper) = ".XLS" Then
fileExcelType = "Excel 8.0"
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & fileExcel & "';Extended Properties=" & fileExcelType & ";")
Else
fileExcelType = "Excel 12.0"
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & fileExcel & "';Extended Properties=" & fileExcelType & ";")
End If
//Opening excel connection
MyConnection.Open()
Dim myTableName = MyConnection.GetSchema("Tables").Rows(0)("TABLE_NAME")
Dim MyCommand As OleDbDataAdapter = New OleDbDataAdapter(String.Format("SELECT * FROM [{0}] ", myTableName), MyConnection)
MyCommand.TableMappings.Add("Table", " ")
MyCommand.Fill(dt)
//Closing connection
MyConnection.Close()
Remarks:
I used // for the comments because the standar ' was giving some problem here on StackOverflow

Uploading Excel File into MS Access using vb.net

I am trying to import an Excel file into an Access DB via vb.net
the idea is the customer can export the data into excel, modify it, add, delete them importing it back.
The data exported has exactly the same format than the table to import to.
I am using the code below:
Try
Dim strFileName As String = String.Empty
Dim XLda As New OleDbDataAdapter
Dim ExcelTables As New DataTable
Dim StrSelect = "SELECT * FROM [{0}]"
OpenFileDialog1.FileName = ""
OpenFileDialog1.InitialDirectory = mdlGlobalStuff.sMasterDataPath
OpenFileDialog1.Filter = "Excel|*.xls|All files (*.*)|*.*"
If OpenFileDialog1.ShowDialog() <> Windows.Forms.DialogResult.OK Then
Exit Sub
End If
strFileName = OpenFileDialog1.FileName
Dim MyXLConnection As New OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & strFileName & ";Extended Properties=Excel 8.0;")
Using MyXLConnection
Using cmd As New OleDbCommand
cmd.Connection = MyXLConnection
cmd.CommandText = "INSERT INTO [MS Access;Database=InvoicingToolDB.accdb].[tbl_Bases] SELECT * FROM [Sheet1$]"
If MyXLConnection.State = ConnectionState.Open Then
MyXLConnection.Close()
End If
MyXLConnection.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
MsgBox("ImportLinkLabel_LinkClicked: Importing Base data" & vbCrLf & ErrorToString())
End Try
I always have an error message saying:
Unrecognized database format 'c:\--path to db--\InvoicingToolDB.accdb'
The path is correct and I don't understand why the format wouldn't be recognized.
Ok I have found the issue. The OLEDB Provider version was not the right one (4.0 is not reading Access .accdb format but old .mdb format only)
Replacing:
Dim MyXLConnection As New OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & strFileName & ";Extended Properties=Excel 8.0;")
With:
Dim MyXLConnection As New leDbConnection("provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & strFileName & ";Extended Properties=Excel 8.0;")
Works perfectly.

could not find installable isam [vb.net]

I have the following problem, by using the connection string:
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename +
";Extended Properties=Excel 12.0 Xml;"
Then, I can execute the open-task. Nevertheless, if I want to use the following connection string:
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename +
";Extended Properties=Excel 12.0 Xml;HDR=NO"
I get a mistake, saying me that the installable isam could not be found.
What is wrong with the second connection string, as I need this one because in my worksheet no headers are used.
Thanks in advance
if you want to query excel you must have a '$' sign after the sheet name in order to define the sheet as a table.
anyway that is the code i wrote for that purpose:
Try
Dim Myconnetion As New OleDbConnection
Dim DataSet As System.Data.DataSet
Dim MyCOmmand As System.Data.OleDb.OleDbDataAdapter
Dim Path As String = fullpath
Myconnetion = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Path + ";Extended Properties=Excel 12.0;")
MyCOmmand = New System.Data.OleDb.OleDbDataAdapter("SELECT * FROM " & "[" & sheetname & "$]")
DataSet = New System.Data.DataSet
MyCOmmand.Fill(DataSet)
dgv.DataSource = DataSet.Tables(0)
Myconnetion.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try

Getting "data type mismatch in criteria expression" when I am trying to save date in excel vb form

I have a user form from which I want to save data into excel, I can save a normal string and integer but when I am trying to save data from Label13(contains date selected from calendar) in below code, it gives me error as "data type mismatch in criteria expression"
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim dataSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Dim path As String = "D:\Hotel\RoomAvailability.xls"
Dim Sqlq As String
Dim Booked_From As string = Label13.Text
Dim Room_Number As String = 202
MsgBox(Booked_From)
MsgBox(Room_Number)
Sqlq = "Update [Sheet1$] Set [Booked_From] = "
Sqlq = Sqlq & "'" & Booked_From & "'"
Sqlq = Sqlq & " where [Room_Number] ="
Sqlq = Sqlq & "'" & Room_Number & "'"
MsgBox(Sqlq)
MyConnection = New System.Data.OleDb.OleDbConnection( "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter(Sqlq, MyConnection)
dataSet = New System.Data.DataSet
MyCommand.Fill(dataSet)
DataGridView1.DataSource = dataSet.Tables(0)
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
Also what should be the format of cell in Excel in which i want to store date from Label13 ?

Error when trying to read data from Excel in VB.Net

I've tried many different routes in being able to build a page that allows the user to choose an excel file and then reads data from that file. So far all I've gotten is errors.
My latest error is: "Cannot update. Database or object is read-only."
Here is my code:
Protected Sub Upload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Upload.Click
If (testFile.HasFile) Then
Dim ds As DataSet
Dim strFileType As String = System.IO.Path.GetExtension(testFile.FileName).ToString().ToLower()
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Dim MyConnection As System.Data.OleDb.OleDbConnection
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & testFile.FileName & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2")
' Select the data from Sheet1 ([in-house$]) of the workbook.
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
ds = New System.Data.DataSet
MyCommand.Fill(ds) - __This is where the error points.__
grvExcelData.DataSource = ds.Tables(0)
End If
End Sub
Any ideas on why this is being thrown? I'm just trying to output the data to a gridview for now. Later I will need to loop through each cell, but I'm trying one step at a time.
Also, if there's a better way to do this I am completely open to it!
Thanks!
But strFileType is the extension of the file that you wish to open. (I.E. for filename.xls it is just the .xls part)
Probably you want the full file name.
MyConnection = New System.Data.OleDb.OleDbConnection( _
"provider=Microsoft.Jet.OLEDB.4.0; " & _
"data source=" & testFile.FileName & "; " & _
"Extended Properties=Excel 8.0")
Now, for the 'better part':
You don't close the connection, and this should never happen.
A simple Using block will save you
Using MyConnection = New OleDbConnection( _
"provider=Microsoft.Jet.OLEDB.4.0; " & _
"data source=" & strFileType & "; " & _
"Extended Properties=Excel 8.0")
' Select the data from Sheet1 ([in-house$]) of the workbook.
Using MyCommand = New OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
Dim ds = New System.Data.DataSet
MyCommand.Fill(ds)
End Using
End Using
And I suggest to add the Import directive to avoid the lenghty namespace prefix for every single OleDb variable