VB.NET打开Excel文件,并读取里面的数据

作者在 2010-03-17 20:43:58 发布以下内容
本例将打开excel文件,并将数据筛选后传给DataGrid控件
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        'Create variables that are used in code sample.


        ' Create connection string variable. Modify the "Data Source" parameter as
        ' appropriate for your environment.
        Dim sConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" _
                    & "Data Source=E:\myexl.xls;" & _
                     "Extended Properties=Excel 8.0;"

        ' Create the connection object by using the preceding connection string.
        Dim objConn As New OleDbConnection(sConnectionString)

        ' Open connection with the database.
        objConn.Open()

        ' The code to follow uses a SQL SELECT command to display the data from the worksheet.
        MsgBox("成功打开连接")
        ' Create new OleDbCommand to return data from worksheet.
        Dim objCmdSelect As New OleDbCommand("SELECT * FROM [11$] where 姓名='李三'", objConn)

        ' Create new OleDbDataAdapter that is used to build a DataSet
        ' based on the preceding SQL SELECT statement.
        Dim objAdapter1 As New OleDbDataAdapter()

        ' Pass the Select command to the adapter.
        objAdapter1.SelectCommand = objCmdSelect

        ' Create new DataSet to hold information from the worksheet.
        Dim objDataset1 As New DataSet()

        ' Fill the DataSet with the information from the worksheet.
        objAdapter1.Fill(objDataset1, "XLData")

        ' Build a table from the original data.
        DataGrid1.DataSource = objDataset1.Tables(0).DefaultView


        ' Clean up objects.
        objConn.Close()
    End Sub
 
VB.NET技术学习 | 阅读 4841 次
文章评论,共0条
游客请输入验证码
浏览95264次
最新评论