如何将VB.Net连接到Excel作为数据库连接?

时间:2014-03-21 11:20:19

标签: vb.net excel-vba vba excel

我需要使用microsoft excel进行数据库连接,但我不知道应该使用哪些代码 使用。我只能在访问和VB之间建立连接,但在excel中我无法

我在网上复制了这个,但它对我不起作用

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Dim MyConnection As System.Data.OleDb.OleDbConnection
    Dim DtSet As System.Data.DataSet
    Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
    'Fill the [Excel file fullpath] with specific value
    MyConnection = New System.Data.OleDb.OleDbConnection _
    ("provider=Microsoft.ACE.OLEDB.12.0;Data Source= E:\DATABASE\VBtoExcel\VBtoExcel\bin\DataBaseExcel.xlsx; Extended Properties=Excel 12.0;")
    MyCommand = New System.Data.OleDb.OleDbDataAdapter _
        ("select * from [Sheet1]", MyConnection)
    MyCommand.TableMappings.Add("Table", "TestTable")
    DtSet = New System.Data.DataSet
    MyCommand.Fill(DtSet)
    DataGridView1.DataSource = DtSet.Tables(0)
    MyConnection.Close()

End Sub

2 个答案:

答案 0 :(得分:2)

从一张Excel文件中选择的语法需要在工作表名称末尾加上$字符。

MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
                                                                  ^^^^^^^^^^

System.Data.OleDb的提示add the Import Statement到您的文件。所以你可以输入更短的名字

MyCommand = New OleDbDataAdapter("select * from [Sheet1$]", MyConnection)

答案 1 :(得分:0)

Imports System.Data.OleDb

Public Class Form1
    Dim cn As New OleDbConnection
    Dim cm As New OleDbCommand


    Private Sub BtnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSave.Click
        cn.ConnectionString = "provider=microsoft.jet.oledb.4.0;data source =O:\design\Connect to Excel\Agent.xls;extended properties=excel 8.0;"
        cn.Open()

        With cm
            .Connection = cn
            .CommandText = "insert into [Data Agent$]values('" & TxtId.Text & "','" & TxtName.Text & "')"
            .ExecuteNonQuery()

        End With
        cn.Close()
        MsgBox("Sucessfully", MsgBoxStyle.Information, Text)


    End Sub

    Private Sub BtnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnClose.Click
        ' Close()

    End Sub
End Class