vb.net excel to datatable - sql

I have an excel file that has 3 sheets,
I was able to read those sheets into 3 different variables as datatable.
is there any way to run sql query on any datatable
please check the last line (my invention code)
here is my code:
Dim table_customers As DataTable
Dim table_materials As DataTable
Dim table_movement As DataTable
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel + ";Extended Properties=Excel 12.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [accounts$]", MyConnection)
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
table_customers = DtSet.Tables(0)
MyConnection.Close()
MsgBox("customers ok")
Dim sql = "select cusomer_name from '" & table_customers & "' where condition inner join '" & table_materials & "' on ..... "

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

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 ?

Datagridview WHERE SQL Error

I'm trying to automatically fill a datagridview upon loading. This is what I have so far
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Administratot\Downloads\RailwayDatabase2.accdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * from tbl_shifts WHERE EmployeeName = '" & EmployeeLogin.usersname & "' AND Completed = True", MyConn)
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView2.DataSource = view
When I attempt this, I am met with an error reading
Cannot find table 0.
You must fill the dataset first.
da = New OleDbDataAdapter("Select * from tbl_shifts WHERE EmployeeName = '" & EmployeeLogin.usersname & "' AND Completed = True", MyConn)
da.Fill(ds)
Dim view As New DataView(tables(0))
This might help. Keep it simple.
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Administratot\Downloads\RailwayDatabase2.accdb"
Dim MyConn As New OleDbConnection(connString)
Dim da As OleDbDataAdapter
Dim ds As DataSet
--For error handling, do this
Try
'Open the connection
MyConn.Open()
'Fill the dataset
da = New OleDbDataAdapter("Select * from tbl_shifts WHERE EmployeeName = '" & EmployeeLogin.usersname & "' AND Completed = True", MyConn)
ds = New DataSet
da.Fill(ds)
'Fill datagridview
DataGridView2.DataSource = ds.Tables(0)
'Close the connection
MyConn.Close()
Catch ex As Exception
'Make sure connection is closed
If MyConn.State <> ConnectionState.Closed Then MyConn.Close()
End Try
And of course, you will put second group of code in Form_Load Event.

Trying to read this csv file in vb, then response.write the data in the csv out

I'm getting Server Error in '/' Application.
Invalid argument.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: Invalid argument.
when I try to use MyCommand.Fill to read the DataSet
Here's my code
Dim sheets as new List(Of String)(New String(){"po"})
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft Office 12.0 Access Database Engine OLE DB Provider;Data Source=" & filepath & ";Extended Properties=Excel 8.0;")
for p as integer = 0 to sheets.count - 1
dim dt as DataTable
MyCommand = New System.Data.OleDb.OleDbDataAdapter("Select * from ["& sheets(p) & "$]", MyConnection)
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
dt = DtSet.Tables(0)
if p > 0
response.write(sheets(p))
end if
next
MyConnection.Close()
I have a few concerns:
Is there a reason you are using Microsoft Office 12.0 Access Database Engine OLE DB Provider? How about using Microsoft.Jet.OLEDB.4.0?
Are you sure your DB connection (i.e. MyConnection) is open?
You also dont want your users getting unhandled errors. Look into using Try/Catch in this example.
First try to open the connection by calling MyConnection.Open()
Dim sheets as new List(Of String)(New String(){"po"})
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft Office 12.0 Access Database Engine OLE DB Provider;Data Source=" & filepath & ";Extended Properties=Excel 8.0;")
MyConnection.Open() '<-------------------- open the connection here
for p as integer = 0 to sheets.count - 1
dim dt as DataTable
MyCommand = New System.Data.OleDb.OleDbDataAdapter("Select * from ["& sheets(p) & "$]", MyConnection)
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
dt = DtSet.Tables(0)
if p > 0
response.write(sheets(p))
end if
next
MyConnection.Close()

How do you assign a column type when loading csv to datatable?

I'm importing a csv file into a datatable using this code:
Dim connstr As String
connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & varFilePath & ";Extended Properties=Text;"
Dim conn As New OleDbConnection
conn = New OleDbConnection(connstr)
Try
conn.Open()
Dim strsql As String
strsql = "SELECT * FROM [" & varFileName & "]"
Dim da As New OleDbDataAdapter()
da = New OleDbDataAdapter(strsql, conn)
'dt con informacion de archivo
Dim dtInfo As New DataTable
da.Fill(dtInfo)
da.Dispose() ...
But there is a column in the CSV file that has some values that starts with zeros '000561' for example. When the datatable is filled it just stores '561'.
Do you know how can i set the datatype o the column to recognize the values as char and not as integers?
Thanks very much for your time and help.
Regards.