i'm building an import routine for my application - the goal is to have the user be able to select an excel spreadsheet that looks identical to my sql server database table.
so far, i've built a small prototype and the code looks like this:
I am able to select the excel file, have it appear in the datagrid. but when i try the import, i get an error message:
Update unable to find TableMapping['Table'] or Datatable 'Table'.
I'm not sure what i'm doing wrong. Also, how do i handle scenarios where the record already exists in the database... do i have to attempt to insert each record one at a time, checking if it already exists first?
so far, i've built a small prototype and the code looks like this:
VB.NET:
Private Sub btnImport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImport.Click
Try
Dim DtSet As System.Data.DataSet
Dim excelConnection As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source='" & strFileToOpen & "';Extended Properties=""Excel 8.0;HDR=YES;IMEX=0""")
DtSet = New System.Data.DataSet
excelConnection.Open()
Dim excelCommand As New System.Data.OleDb.OleDbDataAdapter("INSERT INTO [ODBC; Driver={SQLServer};Server=(local);Database=territoreLIVE;Trusted_Connection=yes].[Householder]SELECT * FROM [Sheet1$];", excelConnection)
excelCommand.Update(DtSet)
excelConnection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub btnReadExcel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReadExcel.Click
'Get user to select file.
If Not (OpenFileDialog1.ShowDialog() = DialogResult.OK) Then
'MsgBox("problems with the Open File Dialog. Contact your administrator.")
Exit Sub
End If
'2007.07.30 Enable MultiFile Selects
strFileToOpen = OpenFileDialog1.FileName
Dim MyConnection As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source='" & strFileToOpen & "';Extended Properties=""Excel 8.0;HDR=YES;IMEX=0""")
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Try
'MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from A1:L57", MyConnection)
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
DataGridView1.DataSource = DtSet.Tables(0).DefaultView
MyCommand = Nothing
DtSet = Nothing
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
I am able to select the excel file, have it appear in the datagrid. but when i try the import, i get an error message:
Update unable to find TableMapping['Table'] or Datatable 'Table'.
I'm not sure what i'm doing wrong. Also, how do i handle scenarios where the record already exists in the database... do i have to attempt to insert each record one at a time, checking if it already exists first?