我正在创建一个需要现有 Excel 文件中的一些数据的程序。我想向在表单中创建的 VB 程序消息框显示几个 Cell 的值。如何在 VB-2008 中获得它?请帮忙。
问问题
238 次
1 回答
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
于 2013-09-10T05:31:27.670 回答