表形式(リスト形式?)のエクセルのデータをデータテーブル(DataTable)に取り込むには。
PCにインストールされているExcelバージョン:Excel2003
Visual Studio 2010
例)エクセルの中身
ID 名前 内容
1 名前1 ないよう1
2 名前2 ないよう2
3 名前3 内容がないよう
Dim filePath As String = "ファイルのフルパス"
Dim Con As New OleDb.OleDbConnection
Dim Command As New OleDb.OleDbCommand()
Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=" & _
filePath & ";" & _
"Extended Properties=""Excel 8.0;HDR=YES;"""
Dim oDataTable1 As DataTable = New DataTable
'条件を指定してデータを取得したい場合
Dim where As String = " WHERE 内容 '内容がないよう'"
Try
Dim oDataAdapter As New OleDb.OleDbDataAdapter
Con.ConnectionString = ConnectionString
Command.Connection = Con
'これは、シート名が「Sheet1」のときの例。 Sheet1じゃないときはは、[Sheet1$]の「Sheet1」のところを書き換え
Command.CommandText = "SELECT * FROM [Sheet1$]" & where
oDataAdapter.SelectCommand = Command
oDataAdapter.Fill(oDataTable1)
Catch ex As Exception
'エラー処理
Finally
If Not Command Is Nothing Then
Command.Dispose()
End If
If Not Con Is Nothing Then
Con.Dispose()
End If
End Try
Return oDataTable1
データテーブルの中身
(項目名)ID 名前 内容
1 名前1 ないよう1
2 名前2 ないよう2