Excel to SQL Table with VB.net - sql

I've read all the articles and posts from other users on this subject and I'm still stuck.
Essentially what I have is a VB.net program with a local SQL backend. I created a table called "consolDump" that I wish to import an Excel sheet into. I feel like I'm very close just from the help I've gotten from the other people with a similar problem. Just to clarify, I do not have the ability to add software to the machine I'm using (it's heavily restricted by IT), and do not have access to the SQL server import utility.
Here's the code I have. Any help would be appreciated.
Imports System.Data.SqlClient
Public Class formImport
Private Sub buttonConsolImport_Click(sender As Object, e As EventArgs) Handles buttonConsolImport.Click
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Dim fBrowse As New OpenFileDialog
Dim fname As String
Try
With fBrowse
.Filter = "Excel files(*.xls)|*.xls|All files (*.*)|*.*"
.FilterIndex = 1
.Title = "Import data from Excel file"
End With
If fBrowse.ShowDialog() = Windows.Forms.DialogResult.OK Then
fname = fBrowse.FileName
MyConnection = New System.Data.OleDb.OleDbConnection _
("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & fname & ";" & "Extended Properties=""Excel 8.0;HDR=NO;IMEX=1""")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("A1, B1, C1, D1, E1, F1, G1, H1, I1, J1, k1, L1 from [consol_data$]", MyConnection)
MyCommand.TableMappings.Add("Table", "consolDump")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
For Each Drr As DataRow In DtSet.Tables(0).Rows
Execute_Local("INSERT INTO consolDump(PO_Number, Consol_ID, Status, Contractor, UTAS_Owner, Description, Start_Date, End_Date, Total_Spend, ) VALUES ('" & Drr(0).ToString & "','" & Drr(1).ToString & "','" & Drr(2).ToString & "'),'" & Drr(3).ToString & "','" & Drr(4).ToString & "','" & Drr(5).ToString & "','" & Drr(6).ToString & "','" & Drr(7).ToString & "','" & Drr(8).ToString & "','" & Drr(9).ToString & "','" & Drr(10).ToString & "','" & Drr(11).ToString & "'")
Next
MsgBox("Success")
MyConnection.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
Ok so, to add to what I've asked, I'm trying to import a csv file from the excel sheet with this code, which works fine.
'Converts consol data to csv file===========================
Dim excelApplication As New Excel.Application
Dim excelWrkBook As Excel.Workbook
excelApplication.Visible = False
excelApplication.DisplayAlerts = False
excelWrkBook = excelApplication.Workbooks.Open("R:\PECOE-WLOX\QuEST\Torres\sqlProjects\consol_data.xls")
excelWrkBook.SaveAs(Filename:="R:\PECOE-WLOX\QuEST\Torres\sqlProjects\consol_data.csv", FileFormat:=Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV)
excelWrkBook.Close()
excelApplication.DisplayAlerts = True
excelApplication.Quit()
MessageBox.Show("Converted to CSV")
'============================================================
Now I'm trying to import the csv file into a new data table but I'm getting a strange error that says "system.data.sql is a namespace and cannot be used as an expression". Now this is probably my inexperience as I pulled the code from another site and several said they have it working. I've modified it to fit my data. Any help would be appreciated. The error appears as a syntax error on "Dim cmd As New SqlClient.SqlCommand(Sql, connection)". It's highlighting the Sql in the paranthesis as a namespace.
Dim consolDump1 As New DataTable()
consolDump1.Columns.Add("PO_Number")
consolDump1.Columns.Add("Consol_ID")
consolDump1.Columns.Add("Status")
consolDump1.Columns.Add("Contractor")
consolDump1.Columns.Add("UTAS_Owner")
consolDump1.Columns.Add("Description")
consolDump1.Columns.Add("Start_Date")
consolDump1.Columns.Add("End_Date")
consolDump1.Columns.Add("Total_Spend")
consolDump1.Columns.Add("Job_Title")
consolDump1.Columns.Add("Location")
consolDump1.Columns.Add("Type")
Dim parser As New FileIO.TextFieldParser("R:\PECOE-WLOX\QuEST\Torres\sqlProjects\consol_data.csv")
parser.Delimiters = New String() {","} ' fields are separated by comma
parser.HasFieldsEnclosedInQuotes = True ' each of the values is enclosed with double quotes
parser.TrimWhiteSpace = True
parser.ReadLine()
Do Until parser.EndOfData = True
consolDump1.Rows.Add(parser.ReadFields())
Loop
Dim strSql As String = "INSERT INTO consolDump(PO_Number,Consol_ID,Status,Contractor,UTAS_Owner,Description,Start_Date,End_Date,Total_Spend,Job_Title,Location,Type) VALUES (#PO_Number,#Consol_ID,#Status,#Contractor,#UTAS_Owner,#Description,#Start_Date,#End_Date,#Total_Spend,#Job_Title,#Location,#Type)"
Dim SqlconnectionString As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\consolData.mdf;Integrated Security=True;Connect Timeout=30"
Using connection As New SqlClient.SqlConnection(SqlconnectionString)
Dim cmd As New SqlClient.SqlCommand(Sql, connection)
' create command objects and add parameters
With cmd.Parameters
.Add("#PO_Number", SqlDbType.VarChar, 15, "PO_Number")
.Add("#Consol_ID", SqlDbType.BigInt, "Consol_ID")
.Add("#Status", SqlDbType.Text, "Status")
.Add("#Contractor", SqlDbType.Text, "Contractor")
.Add("#UTAS_Owner", SqlDbType.Text, "UTAS_Owner")
.Add("#Description", SqlDbType.Text, "Description")
.Add("#Start_Date", SqlDbType.Date, "Start_Date")
.Add("#End_Date", SqlDbType.Date, "End_Date")
.Add("#Total_Spend", SqlDbType.Money, "Total_Spend")
.Add("#Job_Title", SqlDbType.Text, "Job_Title")
.Add("#Location", SqlDbType.Text, "Location")
.Add("#Type", SqlDbType.Text, "Type")
End With
Dim adapter As New SqlClient.SqlDataAdapter()
adapter.InsertCommand = cmd
'--Update the original SQL table from the datatable
Dim iRowsInserted As Int32 = adapter.Update(consolDump1)
End Using
End Sub

There is an extra comma at the end of the column list in your sql query:
End_Date, Total_Spend, )
You need this:
End_Date, Total_Spend )
Also, the column list has 9 items, but your values list has 12. Are you maybe missing a few columns?
Finally for this section, it doesn't matter much with code for personal use, but what you're doing with string concatenation to put the excel data into your query is considered bad practice. If you do that in product code, you're creating a huge security hole. Instead, learn about parameterized queries.
In the later sample, you define your sql string this way:
Dim strSql As String
But try to include in your command this way:
Dim cmd As New SqlClient.SqlCommand(Sql, ...
You should do this:
Dim cmd As New SqlClient.SqlCommand(strSql, ...
Also, based on the other code, if this is an access database, you should still be using the OleDbCommand and OleDbConnection objects, in the System.Data.OleDb namespace.
What I would do is somewhere in between your first sample and your second:
Imports System.Data.SqlClient
Private Sub buttonConsolImport_Click(sender As Object, e As EventArgs) Handles buttonConsolImport.Click
Dim fBrowse As New OpenFileDialog
With fBrowse
.Filter = "Excel files(*.xls)|*.xls|All files (*.*)|*.*"
.FilterIndex = 1
.Title = "Import data from Excel file"
End With
If fBrowse.ShowDialog() <> Windows.Forms.DialogResult.OK Then Exit Sub
Dim fname As String = fBrowse.FileName
Dim sql As String = "INSERT INTO consolDump(PO_Number,Consol_ID,[Status],Contractor,UTAS_Owner,Description,Start_Date,End_Date,Total_Spend,Job_Title,Location,Type) VALUES (#PO_Number,#Consol_ID,#Status,#Contractor,#UTAS_Owner,#Description,#Start_Date,#End_Date,#Total_Spend,#Job_Title,#Location,#Type)"
Try
Dim parser As New FileIO.TextFieldParser(fname)
parser.Delimiters = New String() {","} ' fields are separated by comma
parser.HasFieldsEnclosedInQuotes = True ' each of the values is enclosed with double quotes
parser.TrimWhiteSpace = True
parser.ReadLine() 'skip column headers
Using cn As New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\consolData.mdf;Integrated Security=True"),
cmd As New SqlCommand(sql, cn)
With cmd.Parameters
.Add("#PO_Number", SqlDbType.VarChar, 15)
.Add("#Consol_ID", SqlDbType.BigInt)
.Add("#Status", SqlDbType.Text) 'I doubt that "Text" is the right type for all of these
.Add("#Contractor", SqlDbType.Text) 'If it is, you may want to examine your table schema
.Add("#UTAS_Owner", SqlDbType.Text)
.Add("#Description", SqlDbType.Text)
.Add("#Start_Date", SqlDbType.Date)
.Add("#End_Date", SqlDbType.Date)
.Add("#Total_Spend", SqlDbType.Money)
.Add("#Job_Title", SqlDbType.Text)
.Add("#Location", SqlDbType.Text)
.Add("#Type", SqlDbType.Text)
End With
cn.Open()
Do Until parser.EndOfData = True
Dim fields() As String = parser.ReadFields()
For i As Integer = 0 To 11
cmd.Parameters(i).Value = fields(i)
Next
cmd.ExecuteNonQuery()
Loop
End Using
MsgBox("Success")
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub

Related

Issue with data type importing csv file into sql in vb.net (SqlBulkCopy)

I'm trying to automate the import of csv data into sql. All files, but one are imported ok, so there is no issue with the code. This particular file has a mixed data type column. And when importing data, it loads data as Double, instead of String. As a result, the values that have words, are imported as null. I tried to convert that column into String (ds.Tables(0).Columns(4).DataType), but it makes no difference. When I try to check the type right after the conversion attempt, it shows runtime type, not a string. I have spent a few days researching similar issues and tried everything I could find. Hopefully someone here can offer help on converting the column properly, as it doesn't work for me. Please see the code below. Thanks!
Private Sub ImportIntoSqlBulk(SqlConnString As SqlConnection, ConnStringSql As String, TableNameSql As String, Filenmcsv As String)
SqlConnString.ConnectionString = ConnStringSql
SqlConnString.Open()
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(SqlConnString)
bulkCopy.DestinationTableName = TableNameSql
Try
bulkCopy.WriteToServer(GetCsvData(PathImpt, Filenmcsv))
SqlConnString.Close()
Catch ex As Exception
Email_Subject = "Financial Data Import from Excel Error"
successflag = "N"
Email_Body = "There was an error importing data into " & TableNameSql & " from excel. Error message: " & ex.Message
Send_Email()
SqlConnString.Close()
Exit Sub
End Try
End Using
End Sub
Public Function GetCsvData(ByVal strFolderPath As String, ByVal strFileName As String) As DataTable
Dim strConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFolderPath & ";Extended Properties=""Text;HDR=YES;IMEX=1"""
Dim strConnString2 As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFolderPath & ";Extended Properties=""Text;HDR=YES;IMEX=1;MaxScanRows=0"""
Dim conn2 As New OleDbConnection(strConnString2)
Dim conn As New OleDbConnection(strConnString)
Try
conn.Open()
Dim cmd As New OleDbCommand("SELECT * FROM [" & strFileName & "]", conn)
Dim da As New OleDbDataAdapter()
da.SelectCommand = cmd
Dim ds As New DataSet()
da.Fill(ds)
If strFileName = "CheckRegister.csv" Then
Convert.ToString(ds.Tables(0).Columns(4).DataType)
ds.Tables(0).Columns(4).DataType.GetType()
End If
da.Dispose()
Return ds.Tables(0)
Catch ex As Exception
Return Nothing
Finally
conn.Close()
End Try
End Function

How to take data from access data to Combobox

Public Class AdminP_Time2
Dim conn As OleDbConnection
Dim cmd As OleDbCommand
Dim sql As String
Dim dr As OleDbDataReader
Private Sub AdminP_Time2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database.accdb;Persist Security Info=False;")
conn.Open() 'opens the connection
sql = "SELECT * FROM LecturerName"
cmd = New OleDbCommand(sql, conn)
dr = cmd.ExecuteReader
If dr.Read = True Then
ComboBox1.Text = dr("LecturerName")
End If
why my combobox just show me 1 item ? can anyone help me ? i want take my access data to Combobox.
The reason that your own code doesn't work is that you're only reading one record. You need a loop, e.g.
While dr.Read()
ComboBox1.Items.Add(dr("LecturerName"))
End While
That said, your code should look more like this:
Using conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database.accdb;Persist Security Info=False;"),
cmd As New OleDbCommand("SELECT * FROM LecturerName", conn)
conn.Open()
Using dr As OleDbDataReader = cmd.ExecuteReader()
Dim tbl As New DataTable
tbl.Load(dr)
With ComboBox1
.DisplayMember = "LecturerName"
.DataSource = tbl
End With
End Using
End Using
That will load the data into a DataTable and bind that to the ComboBox. You should also set the ValueMember of the ComboBox if you want to be able to access the PK value of the selected record via the SelectedValue of the ComboBox. You should also specify what columns you want to retrieve data from rather than using a wildcard unless you genuinely want every column.
Here is a good example.
Sub TryThis()
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strSQL As String
Set db = CurrentDb
Set qdf = db.QueryDefs("qryStaffListQuery”)
strSQL = "SELECT tblStaff.* ” & _
"FROM tblStaff ” & _
"WHERE tblStaff.Office='" & Me.cboOffice.Value & "’ ” & _
"AND tblStaff.Department='" & Me.cboDepartment.Value & "’ ” & _
"AND tblStaff.Gender='" & Me.cboGender.Value & "’ ” & _
"ORDER BY tblStaff.LastName,tblStaff.FirstName;”
End Sub
You can find all details from the link below.
http://www.fontstuff.com/access/acctut17.htm

Adding data from Text boxes directly to database and viewing updated gridview

still very new to this and can't seem to find exactly what I'm looking for. Quick run-through on what I'm trying to accomplish. I have a datagridview (3 columns - Id, Name, Address) that is connected to a local .mdf database file, that I'm able to search through using a search textbox. My goal NOW is to submit records into the database directly using 2 text fields and the Id field to automatically increment. (Id++, txtName.Text, txtAddress.Text) and to use a send button(btnSend) to activate this event.(PLEASE KEEP IN MIND, MY GOAL IS TO HAVE EVERYONE INCLUDING THE NEW RECORD SHOW UP IN THE DATAGRIDVIEW AND FOR THE NEW ROW TO BE INSERTED DIRECTLY TO THE DATABASE AND SAVE ANY CHANGES) I've been hammering at this for a couple days now and would appreciate any help. Below is my code, but please keep in mind I'm still new and trying to figure this language out so if there's any unnecessary code, please do let me know... Also if you want to help with one additional thing, maybe some code on how to export that table to a different file from an export button. Thanks! I'm currently also getting an error saying "Cannot find table 0." when I click the btnSend button.
Public Sub btnSend_Click(ByVal sender As Object, e As EventArgs) Handles btnSend.Click
Try
Dim connectionString As String
Dim connection As SqlConnection
Dim ds As New DataSet("Table")
Dim dataset As New DataSet()
Dim sqlInsert As String
Dim sqlSelect As String
Dim Id As Integer = 5
Dim newRow As DataRow = dataset.Tables(0).NewRow()
connectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=""" & My.Application.Info.DirectoryPath & "\Database1.mdf"";Integrated Security=True;"
sqlInsert = "INSERT INTO Table (#Id, #Name, #Address) VALUES (" & Id & ", '" & txtName.Text & "','" & txtAddress.Text & "')"
sqlSelect = "SELECT * FROM Table"
connection = New SqlConnection(connectionString)
Dim da As New SqlDataAdapter()
connection.Open()
da.Fill(ds)
Using da
da.SelectCommand = New SqlCommand(sqlSelect)
da.InsertCommand = New SqlCommand(sqlInsert)
da.InsertCommand.Parameters.Add(New SqlParameter("Id", SqlDbType.Int, 4, Id))
da.InsertCommand.Parameters.Add(New SqlParameter("Name", SqlDbType.NText, 50, txtName.Text))
da.InsertCommand.Parameters.Add(New SqlParameter("Address", SqlDbType.NText, 50, txtAddress.Text))
Using dataset
da.Fill(dataset)
newRow("Id") = Id
newRow("Name") = txtName.Text
newRow("Address") = txtAddress.Text
dataset.Tables(0).Rows.Add(newRow)
da.Update(dataset)
End Using
Using newDataSet As New DataSet()
da.Fill(newDataSet)
End Using
End Using
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
Throw New Exception("Problem loading persons")
End Try
Dim updatedRowCount As String = gvDataViewer.RowCount - 1
lblRowCount.Text = "[Total Row Count: " & updatedRowCount & "]"
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

Type Mismatch when combining two csv files in VB

I had my code working just fine, but when I generated new updated versions of the CSV files it suddenly errors out on me and gives me a type mismatch catch.
Here is the code that I have right now.
Dim A As String = "ADusers.csv"
Dim B As String = "MlnExp.csv"
Dim filePath As String = "C:\CSV"
Try
Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & (filePath) & "\;Extended Properties='text;HDR=Yes'"
Dim sSql As String = "SELECT *" _
& "FROM ([" & (B) & "] B LEFT JOIN [" & (A) & "] A ON B.EmployeeNumber = A.employeeID)"
Dim conn As OleDb.OleDbConnection = New OleDb.OleDbConnection(ConnectionString)
Dim Command As OleDb.OleDbCommand = New OleDb.OleDbCommand(sSql, conn)
Command.CommandType = CommandType.Text
conn.Open()
Dim da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sSql, conn)
Dim dt As DataTable = New DataTable
da.Fill(dt)
DataGrid1.DataSource = dt
DataGrid1.Update()
conn.Close()
lblStatus.Text = "CSV combined... Now saving to file."
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation)
End Try
Before it would go through, combine the two CSV files, and then display them in my datagrid. But now my catch is throwing back
Type mismatch in expression
i would check B.EmployeeNumber = A.employeeID
in both of your file one is a text value (left align) and the other is a a interger(right align)