Create table from Excel file - sql

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

Related

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.

Load Report failed with crystal report

I got an error (load report failed) when trying to print crystal report in my vb.net application
but my problem is (this error hasn't occurred always) maybe after printing unknown number of reports, then once this error has occurred.
Here is my code:
Dim cmd As New OleDbCommand
Dim connp As New OleDbConnection
Dim da As New OleDbDataAdapter
Dim ds As New DataSet
Dim strsql As String
Dim strreprotname As String
Try
connp.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Application.StartupPath & "\report.mdb; Jet OLEDB:Database Password=KNOZ1003"
connp.Open()
ds.Reset()
strsql = "select * from tab3"
cmd.CommandText = strsql
cmd.Connection = connp
da.SelectCommand = cmd
da.Fill(ds)
strreprotname = "cashrpt"
Dim strreportpath As String = Application.StartupPath & "\Reports\" & strreprotname & ".rpt"
Dim rptdocument As New CrystalDecisions.CrystalReports.Engine.ReportDocument
Dim prnset As New Printing.PrinterSettings
Dim pg As New Printing.PageSettings
rptdocument.Load(strreportpath)
rptdocument.SetDataSource(ds.Tables(0))
rptdocument.SetDatabaseLogon("", "", "", Application.StartupPath + "\report.mdb")
prnset.PrinterName = cashprinter
rptdocument.PrintToPrinter(prnset, pg, False)
cmd.Dispose()
connp.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
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 ?

Having trouble with OleDbConnection

I'm working on a program that will go out to an access database, wipe out the records for all 4 of the tables that I specify, before creating a new table in the database that contains all of the data from my Excel "Table of Contents" file. I'm having trouble with the OleDbConnection side of things. It keeps erroring out on the line that contains conn.Open() with the error "Invalid Argument"
My code is as follows:
Private Sub btnAccess_Click(sender As System.Object, e As System.EventArgs) Handles btnAccess.Click
Dim AccessPath As String = ""
Dim com1 As OleDbCommand
Dim com2 As OleDbCommand
Dim com3 As OleDbCommand
Dim com4 As OleDbCommand
Dim DatabaseFile As String = ""
Dim DatabaseFileTitle As String = ""
Dim ExcelFile As String = ""
Dim ExcelFileTitle As String = ""
Dim connect As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ExcelFile & _
";Extended Properties=Excel 12.0;"
OpenFileDialog2.DefaultExt = "*.accdb"
MsgBox("Select the ACCESS FILE from the working directory.", , "BROWSE FOR THE ACCESS DATABASE")
OpenFileDialog2.InitialDirectory = Microsoft.VisualBasic.FileIO.FileSystem.CurrentDirectory
'Text (*.txt)|*.txt|Pictures (*.bmp;*.ico)|*.bmp;*.ico
OpenFileDialog2.Filter = "Access Database (*.accdb)|*.accdb"
OpenFileDialog2.Title = "Select ACCESS DATABASE File."
OpenFileDialog2.ShowDialog()
DatabaseFile = OpenFileDialog2.FileName
DatabaseFileTitle = System.IO.Path.GetFileNameWithoutExtension(OpenFileDialog2.FileName)
OpenFileDialog3.DefaultExt = "*.xlsx"
MsgBox("Select the EXCEL TOC FILE from the working directory.", , "BROWSE FOR THE EXCEL TOC")
OpenFileDialog3.InitialDirectory = Microsoft.VisualBasic.FileIO.FileSystem.CurrentDirectory
'Text (*.txt)|*.txt|Pictures (*.bmp;*.ico)|*.bmp;*.ico
OpenFileDialog3.Filter = "Excel Spreadhseet (*.xlsx)|*.xlsx"
OpenFileDialog3.Title = "Select EXCEL TOC File."
OpenFileDialog3.ShowDialog()
ExcelFile = OpenFileDialog3.FileName
ExcelFileTitle = System.IO.Path.GetFileNameWithoutExtension(OpenFileDialog3.FileName)
Using conn As New OleDbConnection(connect)
Using cmd As New OleDbCommand()
cmd.Connection = conn
cmd.CommandText = "SELECT * INTO [MS Access;Database=" & DatabaseFile & "].[New Table] FROM [Sheet1$]"
conn.Open()
cmd.ExecuteNonQuery()
com1 = New OleDbCommand("delete from tblArtId", conn)
com2 = New OleDbCommand("delete from tblFigure", conn)
com3 = New OleDbCommand("delete from tblSubGroups", conn)
com4 = New OleDbCommand("delete from tblGroups", conn)
com1.ExecuteNonQuery()
com2.ExecuteNonQuery()
com3.ExecuteNonQuery()
com4.ExecuteNonQuery()
conn.Close()
End Using
End Using
MsgBox("Records Deleted")
End Sub
If anyone is curious....my updated code is as follows:
Private Sub btnAccess_Click(sender As System.Object, e As System.EventArgs) Handles btnAccess.Click
Dim AccessPath As String = ""
Dim com1 As OleDbCommand
Dim com2 As OleDbCommand
Dim com3 As OleDbCommand
Dim com4 As OleDbCommand
Dim DatabaseFile As String = ""
Dim DatabaseFileTitle As String = ""
Dim ExcelFile As String = ""
Dim ExcelFileTitle As String = ""
OpenFileDialog2.DefaultExt = "*.accdb"
MsgBox("Select the ACCESS FILE from the working directory.", , "BROWSE FOR THE ACCESS DATABASE")
OpenFileDialog2.InitialDirectory = Microsoft.VisualBasic.FileIO.FileSystem.CurrentDirectory
'Text (*.txt)|*.txt|Pictures (*.bmp;*.ico)|*.bmp;*.ico
OpenFileDialog2.Filter = "Access Database (*.accdb)|*.accdb"
OpenFileDialog2.Title = "Select ACCESS DATABASE File."
OpenFileDialog2.ShowDialog()
DatabaseFile = OpenFileDialog2.FileName
DatabaseFileTitle = System.IO.Path.GetFileNameWithoutExtension(OpenFileDialog2.FileName)
OpenFileDialog3.DefaultExt = "*.xlsx"
MsgBox("Select the EXCEL TOC FILE from the working directory.", , "BROWSE FOR THE EXCEL TOC")
OpenFileDialog3.InitialDirectory = Microsoft.VisualBasic.FileIO.FileSystem.CurrentDirectory
'Text (*.txt)|*.txt|Pictures (*.bmp;*.ico)|*.bmp;*.ico
OpenFileDialog3.Filter = "Excel Spreadhseet (*.xlsx)|*.xlsx"
OpenFileDialog3.Title = "Select EXCEL TOC File."
OpenFileDialog3.ShowDialog()
ExcelFile = OpenFileDialog3.FileName
ExcelFileTitle = System.IO.Path.GetFileNameWithoutExtension(OpenFileDialog3.FileName)
Dim connectExcel As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ExcelFile & _
";Extended Properties=Excel 12.0;"
Dim connectAccess As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DatabaseFile & ";"
Using connExcel As New OleDbConnection(connectExcel)
Using cmd As New OleDbCommand()
cmd.Connection = connExcel
cmd.CommandText = "SELECT * INTO [MS Access;Database=" & DatabaseFile & "].[New Table] FROM [TOC Output for Excel$]"
connExcel.Open()
cmd.ExecuteNonQuery()
connExcel.Close()
End Using
End Using
Using connAccess As New OleDbConnection(connectAccess)
Using cmdAccess As New OleDbCommand()
com1 = New OleDbCommand("delete from tblArtId", connAccess)
com2 = New OleDbCommand("delete from tblFigure", connAccess)
com3 = New OleDbCommand("delete from tblSubGroups", connAccess)
com4 = New OleDbCommand("delete from tblGroups", connAccess)
connAccess.Open()
com1.ExecuteNonQuery()
com2.ExecuteNonQuery()
com3.ExecuteNonQuery()
com4.ExecuteNonQuery()
connAccess.Close()
End Using
End Using
MsgBox("Staging Table has been created. All Records Deleted from Group, SubGroup, Figure, and ArtID tables")
End Sub

Check if value exist in DBF database

I am trying to check if value "IAV-1419" exist in second column (ColName) in database named PROMGL.DBF.
I get this error : No value give for one or more required parameters
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim FilePath As String = "C:\"
Dim DBF_File As String = "PROMGL"
Dim ColName As String = "[NALOG,C,8]"
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV"
cmd = New OleDbCommand("SELECT * FROM PROMGL WHERE [NALOG,C,8] = #NAL")
cmd.Connection = con
con.Open()
cmd.Parameters.AddWithValue("#NAL", "IAV-1419")
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
con.Close()
Label6.Text = "EXIST"
TextBox1.Text = ""
TextBox1.Focus()
Else
Label6.Text = "DOESN'T EXIST"
End If
End Using
I am stuck here, if anyone could please check this code for me.
are you sure that your connectionstring is correct????
Data Source=" & FilePath &
how connection string know the database where it point only to "C:\" i think is missing database name
Another personal suggestion make your code more simple to read in example :
Dim FilePath As String = "C:\"
Dim DBF_File As String = "PROMGL"
Dim ColName As String = "[NALOG,C,8]"
Using con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV")
con.Open()
Using cmd As New OleDbCommand("SELECT * FROM PROMGL WHERE [NALOG,C,8] = #NAL", con
cmd.Parameters.AddWithValue("#NAL", "IAV-1419")
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
Label6.Text = "EXIST"
TextBox1.Text = ""
TextBox1.Focus()
Else
Label6.Text = "DOESN'T EXIST"
End If
End Using
End Using
End Using