如何从Excel工作表获取数据到VB 2008程序?

时间:2013-09-10 05:22:20

标签: visual-studio-2008 excel-vba vba excel

我正在创建一个程序,它需要现有Excel文件中的一些数据。 我想在表单中创建的VB程序消息框中显示几个Cell的值。 我怎样才能在VB-2008中获得它? 请帮忙。

1 个答案:

答案 0 :(得分:1)

我相信以下示例中的“TABLE_NAME”将是Excel文件中第一张工作表的名称。

    Imports System.Data.OleDb
    Imports System.Data

    Private Function getExcelDataTable() As Data.DataTable
                Dim dt As New Data.DataTable

                Dim fileName As String = Server.MapPath("~/Temp/MyExcel.xls")


                Dim xConnStr As String = "Provider=Microsoft.Ace.OLEDB.12.0;" & _
                        "Data Source=" & fileName & ";Extended Properties=""Excel 12.0;IMEX=1"""
                Dim objXConn As New OleDbConnection(xConnStr)
                Try
                    objXConn.Open()
                    Dim dtSchema As Data.DataTable
                    dtSchema = objXConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})
                    Dim sheet1 As String = dtSchema.Rows(0).Item("TABLE_NAME")
                    Dim objCommand As New OleDbCommand("SELECT * FROM [" & sheet1 & "]", objXConn)
                    Dim objDataAdapter As New OleDbDataAdapter()
                    ' retrieve the Select command for the Spreadsheet
                    objDataAdapter.SelectCommand = objCommand
                    objDataAdapter.Fill(dt)
                    objXConn.Close()
                Catch ex As Exception
                    objXConn.Close()
                    Throw ex
                End Try

                Return dt
            End Function