2010-11-13 70 views
0

最初我使用的是Office Interop導入數據,但這對我和我的電腦來說都是頭痛的一半。現在我試圖用ACE加載它,但我的數據網格沒有被填充。一旦啓動並運行,我需要知道如何以其他方式使用這些數據,以及如何從該DataSet中獲取特定的數據單元。順便說一下,我使用的是Visual Studio 2008。如何使用ACE OLEDB將Excel數據導入VB?

現在我有...

Public Function funcUpdate(ByVal sFileLoc As String) As Boolean 
    'Determine connection string properties 
    Dim dbProperty As String 
    If updFileExt = ".xlsx" Then 
     dbProperty = "Excel 12.0 Xml;HDR=No" 
    ElseIf updFileExt = ".xls" Then 
     dbProperty = "Excel 12.0;HDR=No" 
    Else 
     MessageBox.Show("FATAL: File type error on updater", "OHGAWDNO", MessageBoxButtons.OK, MessageBoxIcon.Error) 
     updateTerm() 
     Return False 
    End If 
    Dim dbConn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & updFile & ";Extended Properties=" & dbProperty & ";") 
    Dim dbCommand As New OleDb.OleDbDataAdapter("select * from [sheet1$]", dbConn) 
    Dim dtSet As New DataSet 
    Try 
     dbCommand.TableMappings.Add("Table", "ExcelTest") 
     dbCommand.Fill(dtSet) 
     Form1.DataGrid1.DataSource = dtSet.Tables(0) 
    Catch exlErr As Exception 
    Finally 
     dbConn.Close() 
    End Try 

    updateTerm() 
End Function 
+0

數據集是否被正確填充? – YWE 2010-11-13 05:12:30

+0

我真的不知道該怎麼說。 – 2010-11-13 15:08:08

+0

我刪除了異常捕獲,發現我的連接字符串(圍繞文件名和屬性沒有「」)存在問題,但數據網格仍未被填充。 – 2010-11-13 15:10:24

回答

0

嘗試這樣做。

Dim path As String = "c:\example.xlsx" 
Dim constr As String = [String].Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;" & _ 
              "HDR=YES;IMEX=1;""", path) 
Dim adapter As New OleDbDataAdapter 
Using cn As New System.Data.OleDb.OleDbConnection(constr) 

     Try 
      cmdselcet = New OleDbCommand("SELECT * FROM [Sheet1$]", cn) 
      cn.Open() 

      adapter.SelectCommand = cmdselcet 
      Dim ds As DataSet 
      ds = New DataSet 

      'Display 
      adapter.Fill(ds) 
      DataGridView1.DataSource = ds.Tables(0) 
      MsgBox("Done!") 

     Catch ex As Exception 
      MsgBox(ex.Message) 
     End Try 

    End Using