Click here to Skip to main content
15,893,622 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi guys! Can somebody help me please because I currently have this code for importing Excel files to SQL Server database which work perfectly:

VB
Dim ExcelConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & myTextBox.Text & ";Extended Properties=""Excel 12.0 Xml;HDR=Yes""")
        Dim expr As String = "SELECT * FROM [Sheet1$]"
        Dim objCmdSelect As OleDbCommand = New OleDbCommand(expr, ExcelConnection)
        Dim objDR As OleDbDataReader
        Dim SQLconn As New SqlConnection()

 ExcelConnection.Open()

                    SQLconn.ConnectionString = conString
                    SQLconn.Open()

                    Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(SQLconn)
                        bulkCopy.DestinationTableName = "myTable"

                        Try
                            objDR = objCmdSelect.ExecuteReader
                            bulkCopy.WriteToServer(objDR)
                            objDR.Close()

                            SQLconn.Close()

                            MsgBox("Uploaded.", MsgBoxStyle.Information)

                        Catch ex As Exception
                            MsgBox(ex.ToString)
                        End Try

                    End Using


The output table in SQL database will be:

EMP. NO. / NAME / DEPT.
1234 / John Adams / NULL
4567 / Ryan King / NULL

Since in the uploaded table the DEPT. is NULL, what I need to do now is to import an Excel File with 2 columns only (EMP. NO. / DEPT.) where the existing EMP. NO. is defined already (1234), and the DEPT. will be inputted (say Accounting) which will be inserted in the table which MATCHES the employee numbers.

EMP. NO. / NAME / DEPT.
1234 / John Adams / Accounting
4567 / Ryan King / NULL

Can somebody help me how to revise my code for this? Thanks very much in advance! :)
Posted

1 solution

Steps to do:
1) get the data from Excel into DataTable object (SELECT * FROM [Sheet1$] WHERE NOT [Dept.] IS NULL).
2) update data (you've got 2 ways)
a) (NOT recommended) go through the collection of DataTable.Rows and build command-string to update your data, for example:
VB
"UPDATE [YourTable] SET [Dept] = '" & DataTable.Rows(i).Item("Dept.").Value.ToString() & "'" & vbCr & _
"WHERE [Emp No.] = " & DataTable.Rows(i).Item("Emp No.").Value.ToString

b) (recomended) create a stored procedure to update data, using Dept. and Emp No. as an input parameters, for example:
SQL
CREATE PROCEDURE UpdateDept
    @DeptName NVARCHAR(30),
    @EmpNo INT
AS
    UPDATE [YourTable] SET [Dept.] = @DeptName
    WHERE [Emp No.] = @EmpNo
GO
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900