How to Update sql table with data from excel sheet in vb.net - sql

I am having problem updating sql table with excel sheet. The fact is that, am working on this small project where the user can first of all export or print out a class list with StudentNumber,SubjectID, ClassScore, ExamScore to excel sheet by clicking a button in vb.net application and then edit the sheet by filling in the ClassScore and ExamScore, then upload the sheet back to sql through vb.net.
The question is how to check if the current StudentNumber or row exist in sql table then update the table else insert a new row.
This is my code using the SQLBulk Copy, left with updating the sql table all in vb.net
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ofd As New OpenFileDialog
If ofd.ShowDialog() <> System.Windows.Forms.DialogResult.OK Then Exit Sub
' Dim dgv As System.Windows.Forms.DataGridView
With ofd
.Filter = "Excel files(*.xls)|*.xls|All files (*.*)|*.*"
.FilterIndex = 1
.Title = "Import data from Excel file"
End With
Dim nme As String = ofd.FileName
Import(nme, dgv)
End Sub
Public Shared Function Import(ByVal FileName As String, ByVal dgv As DataGridView) As Boolean
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=" + FileName + ";Extended Properties=Excel 12.0 Xml;")
'MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\vb.net-informations.xls';Extended Properties=Excel 8.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
MyCommand.TableMappings.Add("Table", "Scores")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
dgv.DataSource = DtSet.Tables(0)
MyConnection.Close()
Dim expr As String = "SELECT * FROM [Sheet1$]"
Dim SQLconn As New SqlConnection()
Dim ConnString As String = "Data Source=xxxx-PC;Initial Catalog=TryExcel;Persist Security Info=True;User ID=xx;Password=xxxx"
Dim objCmdSelect As OleDbCommand = New OleDbCommand(expr, MyConnection)
Dim objDR As OleDbDataReader
SQLconn.ConnectionString = ConnString
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(ConnString)
bulkCopy.DestinationTableName = "Scores"
MyConnection.Open()
objDR = objCmdSelect.ExecuteReader
bulkCopy.WriteToServer(objDR)
objDR.Close()
SQLconn.Close()
End Using
Return True
End Function
Private Shared Function safefilename() As String
Throw New NotImplementedException
End Function

Private Sub Upload_Workbook()
Dim t As New Thread(New ThreadStart(Sub()
dt = New DataTable
dt = New DataTable("Table_Name")
dt.Columns.Add("Column_1")
dt.Columns.Add("Column_2)
dt.Columns.Add("Column_3")
dt.Columns.Add("Column_4")
dt.Columns.Add("Column_5")
dt.Columns.Add("Column_6")
dt.Columns.Add("Column_7")
ds = New DataSet
ds.Tables.Add(dt)
Dim i As Integer
For i = 2 To (Cells(1, 11).Text)
dr = dt.NewRow
dr(0) = Cells(i, 1).Text
dr(1) = Cells(i, 2).Text
dr(2) = Cells(i, 3).Text
dr(3) = Cells(i, 4).Text
dr(4) = Cells(i, 5).Text
dr(5) = Cells(i, 6).Text
dr(6) = Cells(i, 7).Text
dt.Rows.Add(dr)
Next i
trans = con.BeginTransaction
Try
Dim row As Integer
While (row < dt.Rows.Count)
Dim cmd As New SqlCommand("Sheet1_Upload", con, trans)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("Column_1", dt.Rows(row).ItemArray(0))
cmd.Parameters.AddWithValue("Column_2", dt.Rows(row).ItemArray(1))
cmd.Parameters.AddWithValue("Column_3", dt.Rows(row).ItemArray(2))
cmd.Parameters.AddWithValue("Column_4", dt.Rows(row).ItemArray(3))
cmd.Parameters.AddWithValue("Column_5", dt.Rows(row).ItemArray(4))
cmd.Parameters.AddWithValue("Column_6", dt.Rows(row).ItemArray(5))
cmd.Parameters.AddWithValue("Column_7", dt.Rows(row).ItemArray(6))
cmd.ExecuteNonQuery()
row = row + 1
End While
trans.Commit()
Catch ex As Exception
MsgBox(ex.Message)
trans.Rollback()
End Try
End Sub))
t.Start()
End Sub
'''''''SQL Stored Procedure'''''''
Create procedure Sheet1_Upload(#Column_1 varchar(50),#Column_2 varchar(50),#Column_3 varchar(50),#Column_4 varchar(50),#Column_5 varchar(50),#Column_6 varchar(50))
as
begin
Insert INTO Table_Name(Column_1,Column_2,Column_3,Column_4,Column_5,Column_6) Values(#Column_1,#Column_2,#Column_3,#Column_4,#Column_5,#Column_6)
end
Please create this project on Visual Basic>Office/Share Point>Excel 2013 Workbook.File Path Image
Then open the workbook using another program.
oXL = CreateObject("Excel.Application")
oXL.Visible = False
oWB = oXL.Workbooks.Open("D:\workbook.xlsm")
oWB.Activate()
oWB.RunAutoMacros(Excel.XlRunAutoMacro.xlAutoOpen)
Use excel Auto_Open macro and sheet changed event in VB.net.

Related

vb.net message: no value given for one or more required parameters

I made a POS project but when i save the data to access database the error is shown:
no value given for one or more required parameters.
My code is:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim MyConnection As OleDb.OleDbConnection = Nothing
Dim MyTransaction As OleDb.OleDbTransaction = Nothing
Try
'create the connection and transaction object
MyConnection = New OleDb.OleDbConnection(My.Settings.dbConnectionString)
MyConnection.Open()
MyTransaction = MyConnection.BeginTransaction
'insert the new recipt
Dim SQL As String = "insert into recipts (ReciptDate, ReciptTotal) values (:0,:1)"
Dim CMD1 As New OleDb.OleDbCommand
CMD1.Connection = MyConnection
CMD1.Transaction = MyTransaction
CMD1.CommandText = SQL
CMD1.Parameters.AddWithValue(":0", Now.Date)
CMD1.Parameters.AddWithValue(":1", TextBox4.Text)
CMD1.ExecuteNonQuery()
CMD1.Dispose()
'get the id for the recipt
SQL = "Select max (reciptId) as MAXID from recipts"
Dim CMD2 As New OleDb.OleDbCommand
CMD2.Connection = MyConnection
CMD2.Transaction = MyTransaction
CMD2.CommandText = SQL
Dim ReciptID As Long = CMD2.ExecuteScalar()
CMD2.Dispose()
'insert the details of the recipt
Dim I As Integer
For I = 0 To DGV2.Rows.Count - 1
'get the values
Dim Barcode As String = DGV2.Rows(I).Cells(0).Value
Dim BuyPrice As Decimal = DGV2.Rows(I).Cells(2).Value
Dim SellPrice As Decimal = DGV2.Rows(I).Cells(3).Value
Dim ItemCount As Integer = DGV2.Rows(I).Cells(4).Value
'next create a command
Dim CMD3 As New OleDb.OleDbCommand
SQL = "insert into ReciptDetails" & _
"(ReciptId, Barcode,ItemCount,ItemBuyPrice,ItemSellPrice)" & _
"Values" & _
"(:0 ,:1 ,:2 ,:3 ,:4)"
CMD3.Connection = MyConnection
CMD3.Transaction = Mytransaction
CMD3.CommandText = SQL
CMD1.Parameters.AddWithValue(":0", ReciptID)
CMD1.Parameters.AddWithValue(":1", Barcode)
CMD1.Parameters.AddWithValue(":2", ItemCount)
CMD1.Parameters.AddWithValue(":3", BuyPrice)
CMD1.Parameters.AddWithValue(":4", SellPrice)
CMD3.ExecuteNonQuery()
CMD3.Dispose()
Next
'all well save the changes
Mytransaction.Commit()
'close conncetion
Mytransaction.Dispose()
MyConnection.Close()
MyConnection.Dispose()
DGV2.Rows.Clear()
TextBox4.Text = ""
Catch ex As Exception
If Mytransaction IsNot Nothing Then
Mytransaction.Rollback()
End If
If MyConnection IsNot Nothing Then
If MyConnection.State = ConnectionState.Open Then
MyConnection.Close()
End If
End If
MsgBox(ex.Message, MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
End Try
End Sub
What is the problem here?
Simple typo. In your CMD3 you're adding all the parameters to CMD1
Hence CMD3 has 5 missing parameters.

cant find Isam installable CSV Files

Hey I am having a problem taking an excel spread sheet and inserting it into a data-grid in Visual Studio 2013 I was wondering if anyone could give me a hand.
Here is the code I have at the moment.
getting the error Could not find installable ISAM only when I have clicked on the csv fle iut works for ll the other files?
OpenFileDialog1.ShowDialog()
Dim filePath As String = OpenFileDialog1.FileName
Dim extension As String = Path.GetExtension(filePath)
Dim header As String = If(rbHeaderYes.Checked, "YES", "NO")
Dim conStr As String, sheetName As String
conStr = String.Empty
Select Case extension
Case ".xls"
'Excel 97-03
conStr = String.Format(Excel03ConString, filePath, header)
Exit Select
Case ".xlsx"
'Excel 07
conStr = String.Format(Excel07ConString, filePath, header)
Exit Select
Case ".csv"
'CSV
conStr = String.Format(ExcelCsv, filePath, header)
Exit Select
End Select
'Get the name of the First Sheet.
Using con As New OleDbConnection(conStr)
Using cmd As New OleDbCommand()
cmd.Connection = con
con.Open()
Dim dtExcelSchema As DataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
sheetName = dtExcelSchema.Rows(0)("TABLE_NAME").ToString()
con.Close()
End Using
End Using
'Read Data from the First Sheet.
Using con As New OleDbConnection(conStr)
Using cmd As New OleDbCommand()
Using oda As New OleDbDataAdapter()
Dim dt As New DataTable()
cmd.CommandText = (Convert.ToString("SELECT * From [") & sheetName) + "]"
cmd.Connection = con
con.Open()
oda.SelectCommand = cmd
oda.Fill(dt)
con.Close()
'Populate DataGridView.
dataGridView1.DataSource = dt
End Using
End Using
End Using
End Sub

Error "Child list for field [Sheet1$] cannot be created" when loading data from excel to datagridview

I am trying to fill the DataGridView (grvExcelData in this case) with data from an excel file. But I am getting the following error:
"Child list for field [Sheet1$] cannot be created"
Below is my code fragment where I am trying to fill the data grid view. Also I am using Visual Studio 2010 for programming
Thanks for your help in advance
Public Sub fillgrid()
Dim conn1 As String
conn1 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filenamepath & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
Dim connection As OleDbConnection = New OleDbConnection(conn1)
Dim da As OleDbDataAdapter = New OleDbDataAdapter("SELECT * FROM [Sheet1$]", connection)
Dim ds As DataSet = New DataSet()
Dim emptyfile As String = "The file does not have any records for inserting."
Dim selectCmd As OleDbCommand = New OleDbCommand()
selectCmd.Connection = connection
selectCmd.CommandText = "SELECT * FROM [Sheet1$]"
If connection.State = ConnectionState.Closed Then
connection.Open()
End If
da.SelectCommand = selectCmd
Dim dsCounter As Integer = da.Fill(ds, "[Sheet1$]")
If dsCounter = 0 Then
MessageBox.Show(emptyfile, "dsCounter")
End If
grvExcelData.DataSource = ds
grvExcelData.DataMember = "Sheet1"
grvExcelData.SelectionMode = DataGridViewSelectionMode.FullRowSelect
da.Dispose()
If connection.State = ConnectionState.Open Then
connection.Close()
connection.Dispose()
End If
End Sub
Change
grvExcelData.DataMember = "Sheet1"
to
grvExcelData.DataMember = "[Sheet1$]"

how to add new column to a database after importing data from xl sheet

I need to import data of a xl sheet to a database and while it is being saved in db i need to add another column to it and save it. I am using following code:-------
Private Sub cmdImport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdImport.Click
Dim _filename As String = txtFile.Text
'Create connection object for xl sheet
Dim _conn As String
_conn = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & _filename & ";" & "Extended Properties=Excel 8.0;"
Dim _connection As OleDb.OleDbConnection = New OleDb.OleDbConnection(_conn)
'List columns you need from the Excel file
Dim _command As New System.Data.OleDb.OleDbCommand("Select * FROM [Sheet1$]", _connection)
'open connection for xl sheet
_connection.Open()
' Create DbDataReader to read Data from xl sheet
Dim dr As System.Data.OleDb.OleDbDataReader = _command.ExecuteReader()
'open connection for database to write into it
cnnOLEDB.Open()
Dim chal_no As String
Try
'reading data from xl sheet utill the last rows
If dr.HasRows() Then
While dr.Read()
'writing the read data from xl sheet into access database
chalan_no = cmbChal_noImport.Text
'getting the parameter values from xl sheet to write into access db
Dim P1 As New OleDb.OleDbParameter
P1.DbType = DbType.String
P1.ParameterName = "sr_no"
P1.Value = dr.GetValue(0)
'adding the parameters in to the db
Dim strSql As String = "INSERT INTO Vendor_Machine(sr_no,chalan_no) VALUES (#srno,#chalan_no)"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(strSql, cnnOLEDB)
cmd.Parameters.AddRange(New OleDb.OleDbParameter() {P1})
cmd.Parameters.AddWithValue("#srno", DbType.String)
cmd.Parameters.AddWithValue("#chalan_no", chalan_no)
cmd.ExecuteScalar()
End While
End If
MsgBox("Xl sheet Import Complete", MsgBoxStyle.OkOnly)
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
Finally
'closing the access and xl sheet connection
cnnOLEDB.Close()
_connection.Close()
End Try
'End Using
End Sub
Problem is that, it doesn't show any error but after saving the data in db , in chalan_no column it shows a constant"16". plz resolve my problem..
Thank you.
I am not sure if this code will solve your problem. But this is bit simpler than yours.
Private Sub cmdImport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdImport.Click
Dim _filename As String = txtFile.Text
'Create connection object for xl sheet
Dim _conn As String
_conn = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & _filename & ";" & "Extended Properties=Excel 8.0;"
Dim _connection As OleDb.OleDbConnection = New OleDb.OleDbConnection(_conn)
'List columns you need from the Excel file
Dim _command As New System.Data.OleDb.OleDbCommand("Select * FROM [Sheet1$]", _connection)
'open connection for xl sheet
_connection.Open()
' Create DbDataReader to read Data from xl sheet
Dim dr As System.Data.OleDb.OleDbDataReader = _command.ExecuteReader()
'open connection for database to write into it
cnnOLEDB.Open()
Dim chal_no As String
Try
'reading data from xl sheet utill the last rows
If dr.HasRows() Then
While dr.Read()
'writing the read data from xl sheet into access database
chalan_no = cmbChal_noImport.Text
'getting the parameter values from xl sheet to write into access db
Dim P1 As New OleDb.OleDbParameter
'P1.DbType = DbType.String
'P1.ParameterName = "sr_no"
'P1.Value = dr.GetValue(0)
'adding the parameters in to the db
Dim strSql As String = "INSERT INTO Vendor_Machine(sr_no,chalan_no) VALUES (?,?)"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(strSql, cnnOLEDB)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.Add("#p1", OleDbType.VarChar).Value = dr.GetValue(0)
.Add("#p2", OleDbType.VarChar).Value = cmbChal_noImport.Text
End With
' cmd.Parameters.AddRange(New OleDb.OleDbParameter() {P1})
'cmd.Parameters.AddWithValue("#srno", DbType.String)
'cmd.Parameters.AddWithValue("#chalan_no", chalan_no)
cmd.ExecuteNonQuery()
'cmd.ExecuteScalar()
End While
End If
MsgBox("Xl sheet Import Complete", MsgBoxStyle.OkOnly)
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
Finally
'closing the access and xl sheet connection
cnnOLEDB.Close()
_connection.Close()
End Try
'End Using
End Sub

failed to read the excel to sql database

I want to upload an Excel file and write data to sql server 2008.
The Excel file has 7 sheets and it writes in 7 tables.
Example : (sheetn -> temp_sheetn)
The code is working well but the last sheet is not writing in the last table.
The code is like this:
Partial Class app_UploadData
Inherits System.Web.UI.Page
Dim apps As New MyApps
Dim GlobReg As Integer = 0
Dim GlobOTC As Integer = 0
Private dt As DataTable = Nothing
Public Function xlsInsert(ByVal pth As String) As System.Data.DataTable
Dim strcon As String = String.Empty
If Path.GetExtension(pth).ToLower().Equals(".xls") OrElse Path.GetExtension(pth).ToLower().Equals(".xlsx") Then
strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & pth & ";Extended Properties=""Excel 8.0;HDR=YES;"""
Else
strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & pth & ";Extended Properties=""Excel 12.0;HDR=YES;"""
End If
Dim strselect As String = "Select * from [Sheet1$]"
Dim exDT As New DataTable()
Using excelCon As New OleDbConnection(strcon)
Try
excelCon.Open()
Using exDA As New OleDbDataAdapter(strselect, excelCon)
exDA.Fill(exDT)
End Using
Catch oledb As OleDbException
Throw New Exception(oledb.Message.ToString())
Finally
excelCon.Close()
End Try
For i As Integer = 0 To exDT.Rows.Count - 1
' Check if first column is empty
' If empty then delete such record
If exDT.Rows(i)("CardNo").ToString() = String.Empty Then
exDT.Rows(i).Delete()
End If
Next
exDT.AcceptChanges()
' refresh rows changes
If exDT.Rows.Count = 0 Then
Throw New Exception("File uploaded has no record found.")
End If
Return exDT
End Using
End Function
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim ds As New DataSet()
Dim XlsConnString As String = String.Empty
Dim DirPath As String = Server.MapPath("~/Temp_Upload/")
Dim fName As String
If (Directory.Exists(DirPath)) Then
For Each fName In Directory.GetFiles(DirPath)
If File.Exists(fName) Then
File.Delete(fName)
End If
Next
End If
If xlsUpload.HasFile Then
Dim fileName As String = Path.GetFileName(xlsUpload.PostedFile.FileName)
Dim fileExtension As String = Path.GetExtension(xlsUpload.PostedFile.FileName)
Dim fileLocation As String = Server.MapPath("~/Temp_Upload/" & fileName)
xlsUpload.SaveAs(fileLocation)
'Check whether file extension is xls or xslx
If fileExtension = ".xls" Then
XlsConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & fileLocation & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=2"""
ElseIf fileExtension = ".xlsx" Then
XlsConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & fileLocation & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
ElseIf fileExtension <> ".xls" Or fileExtension <> ".xlsx" Then
lblMessage.Text = "Upload file must be excel !"
Exit Sub
End If
Dim cmd As New SqlCommand : Dim SheetName As String 'Dim dr As SqlDataReader
'Dim tran As SqlTransaction
apps.OpenConnection()
cmd.Connection = apps.oConn
Dim cn As New OleDbConnection(XlsConnString)
Try
cn.Open()
Catch ex As OleDbException
Console.WriteLine(ex.Message)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
' It Represents Excel data table Schema.
Dim dt As New System.Data.DataTable()
dt = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
If dt IsNot Nothing OrElse dt.Rows.Count > 0 Then
For sheet_count As Integer = 1 To dt.Rows.Count - 1
Try
' Create Query to get Data from sheet.
SheetName = dt.Rows(sheet_count)("table_name").ToString()
'Dim da As New OleDbDataAdapter("SELECT * FROM [" & sheetname & "]", cn)
'da.Fill(ds, sheetname)
'Execute a query to erase any previous data from our destination table
cmd.CommandText = "Truncate Table Temp_" & SheetName
cmd.ExecuteNonQuery()
'Series of commands to bulk copy data from the excel file into our SQL table
Dim OleDbConn As OleDbConnection = New OleDbConnection(XlsConnString)
Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM [" & SheetName & "]"), OleDbConn)
'Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM [Customer$]"), OleDbConn)
OleDbConn.Open()
Dim OleDbRead As OleDbDataReader = OleDbCmd.ExecuteReader()
Dim bulkCopy As SqlBulkCopy = New SqlBulkCopy(apps.oConn)
bulkCopy.DestinationTableName = "Temp_" & SheetName
bulkCopy.WriteToServer(OleDbRead)
OleDbConn.Close()
OleDbConn = Nothing
Catch ex As DataException
Console.WriteLine(ex.Message)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Next
End If
cn.Close()
cn = Nothing
apps.CloseConnection()
End If
End Sub
End Class
The line that reads
For sheet_count As Integer = 1 To dt.Rows.Count - 1
should either be
For sheet_count As Integer = 0 To dt.Rows.Count - 1
or
For sheet_count As Integer = 1 To dt.Rows.Count
The first one I suspect, but I can't remember if this is a zero based list as I haven't got VB.Net installed here.
Incidentally there's no need to check the file extension is .xls and then to use the Jet provider, Microsoft.ACE.OLEDB.12.0 will work just fine on .xls files.