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