|
-
July 16th, 2009, 01:58 PM
#3
Re: Import Excel Data to Dataset
There is no need to open the excel file to know the sheet names. You can use GetOleDbSchemaTable method of the OleDbConnection class to get the schema of the excel file. This way you can then loop through the datatable and then query each sheet. I have changed your code a bit
Code:
Public Function StreamExcelData() As Boolean
Dim Connection As System.Data.OleDb.OleDbConnection
Dim Command As System.Data.OleDb.OleDbDataAdapter
Dim OpenFileDB As New OpenFileDialog
Dim i As Integer
Dim Sheet As String
With OpenFileDB
.Filter = "All files | *.* | Excel files | *.xl*"
.FilterIndex = 2
.InitialDirectory = "C:\My Documents"
.AddExtension = True
.DefaultExt = "xls"
.CheckFileExists = True
.CheckPathExists = True
.Title = "Open Input Source File"
End With
If (OpenFileDB.ShowDialog() = DialogResult.OK) Then
Dim gblSaveNewFile As String = OpenFileDB.FileName
Try
Connection = New System.Data.OleDb.OleDbConnection( _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & gblSaveNewFile & ";" & _
"Extended Properties=""Excel 8.0;HDR=YES;IMEX=1""")
'open connection
Connection.Open()
'get the sheet names from the schema
Dim schemaTable As DataTable = Connection.GetOleDbSchemaTable(Data.OleDb.OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})
'schemaTable now contains the schema of the excel file and sheet names can be retrieved using the TABLE_NAME column
Sheet = schemaTable.Rows(0).Item("TABLE_NAME").ToString()
Command = New System.Data.OleDb.OleDbDataAdapter("SELECT * FROM [" & Sheet & "]", Connection)
Command.TableMappings.Add("MyDataSample", "MyDataSample")
Dim MyDs = New DataSet()
Command.Fill(MyDs)
Connection.Close()
'Rename the column names by replacing the spaces with _ where applicable
For i = 0 To MyDs.Tables(0).Columns.Count - 1
MyDs.Tables(0).Columns(i).ColumnName = Trim(MyDs.Tables(0).Columns(i).ColumnName).Replace(" ", "_")
Next
Dim mytable As DataTable
MyTable = New DataTable("MY_DATA_TABLE")
MyTable = MyDs.Tables(0).Copy
Return True
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
Return False
End Try
Connection.Close()
Else
Return False
End If
End Function
Also could you explain why you are using GC.Collect() method? I don't see any advantage of using that method in this piece of code.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|