วันเสาร์ที่ 9 เมษายน พ.ศ. 2554

การ Import Excel ทั้งหมดลง Datagrid

Public Class Test_Import_Excel

Dim sFilePath, sFileName As String
Dim sSlash As Single

Dim strConnection As System.Data.OleDb.OleDbConnection
Dim myPath As String = sFilePath & sFileName

Private Sub Test_Import_Excel_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'B a s s i e
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
With OpenFileDialog1
.Title = "Import Sage CSV file"
.InitialDirectory = "C:\Documents and Settings\htran\My Documents\vbnet\Welcome"
.Filter = "File (*.xls;*.csv;*.txt)|*.xls;*.csv;*.txt|All files (*.*)|*.*"

.ShowDialog()

sSlash = InStrRev(.FileName, "\")
sFilePath = Mid(.FileName, 1, sSlash)
sFileName = Mid(.FileName, sSlash + 1, Len(.FileName))
TextBox1.Text = .FileName
End With

myPath = sFilePath & sFileName

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try

Dim objDataSet As System.Data.DataSet
Dim objAdapter As System.Data.OleDb.OleDbDataAdapter

strConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source='" & myPath & " '; " & "Extended Properties=Excel 8.0;")
objAdapter = New System.Data.OleDb.OleDbDataAdapter("select * from [sheet1$]", strConnection)
objDataSet = New System.Data.DataSet
objAdapter.Fill(objDataSet, "Customers")
DataGridView1.DataSource = objDataSet.Tables(0).DefaultView
strConnection.Close()

Catch ex As Exception
Dim er As String
strConnection.Close()
End Try
End Sub

End Class

ไม่มีความคิดเห็น:

แสดงความคิดเห็น