【问题标题】:Reading from Excel sheet从 Excel 工作表中读取
【发布时间】:2019-01-27 17:16:27
【问题描述】:

我编写了下面的代码来从 Excel 工作表中读取数据并在 Visual Basic 的组合框中显示数据。

但是,当我点击“运行”时,什么都没有显示。

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim MyConnection As New OleDb.OleDbConnection
        Dim MyCommand As New OleDb.OleDbCommand
        Dim filePath, sql As String
        filePath = "C:\Users\Nour\Desktop\projects\grade10\grade10\atlas.xlsx"
        sql = "Select continent from [Sheet1]"
        MyConnection.ConnectionString = $"Provider= Microsoft.Jet._OLEDB 11.0;data source = {filePath};Extended_Properties=Excel 8.0"
        MyConnection.Open()
        MyCommand.Connection = MyConnection
        MyCommand.CommandText = sql
        Dim da As New OleDb.OleDbDataAdapter
        da.SelectCommand = MyCommand
        Dim dt As New DataTable
        da.Fill(dt)
        Me.ComboBox1.DataSource = dt
        Me.ComboBox1.DisplayMember = dt.Columns(0).ToString


        MyConnection.Close()

【问题讨论】:

  • 我不确定这里的大部分代码,但我很确定您需要在连接字符串中分隔文件路径。用双引号终止前面的字符串,使用 & 符号,然后使用文件路径。在背面反转它。

标签: excel vb.net jet


【解决方案1】:

试试这个代码

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim fname As String = "C:\Users\Nour\Desktop\projects\grade10\grade10\atlas.xlsx"
        Dim connectionStringTemplate As String = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source={0};" + "Extended Properties=""Excel 12.0;HDR=Yes"""
        Dim connectionString As String = String.Format(connectionStringTemplate, fname)
        Dim sqlSelect As String = "SELECT * FROM [Sheet1$];"
        Dim workbook As DataSet = New DataSet()
        Dim excelAdapter As System.Data.Common.DataAdapter = New System.Data.OleDb.OleDbDataAdapter(sqlSelect, connectionString)
        excelAdapter.Fill(workbook)
        Dim worksheet As DataTable = workbook.Tables(0)
        ComboBox1.DataSource = worksheet
        Me.ComboBox1.DisplayMember = worksheet.Columns(0).ToString
    End Sub

【讨论】:

  • System.InvalidOperationException: 'Microsoft.ACE.OLEDB.12.0' 提供程序未在本地计算机上注册。'
  • 我在我的机器上测试了代码,你可以使用 Dim connectionStringTemplate As String = Provider=Microsoft.Jet._OLEDB 11.0;" + "Data Source={0};" + "Extended Properties=" "Excel 8.0;HDR=是"""
【解决方案2】:

要读取 xlsx 文件而不是 xls 文件,您将需要 ACE provider 而不是 JET 提供程序。您需要添加扩展属性“HDR=Yes”来告诉它有一个标题行。

工作表的名称后面需要$

要组成连接字符串,您可以使用连接字符串生成器 - 它会负责添加任何引号或从各个部分创建有效连接字符串所需的任何内容。

DataAdapter 将为您打开和关闭连接。

一些实体使用非托管资源(即它们在使用后不会自动清理) - 它们将有一个 .Dispose() 方法来释放这些资源。或者您可以使用 Using 构造来为您处理。

我使用了ColumnName 属性而不是ToString,因为它更明显。

我制作了一个小的 Excel xlsx 文件来测试并使用了这个程序:

Imports System.Data.OleDb

Public Class Form1

    Sub PopulateCB()
        Dim filepath = "C:\temp\Continents.xlsx"

        Dim csb As New OleDbConnectionStringBuilder
        csb.Provider = "Microsoft.ACE.OLEDB.12.0"
        csb.DataSource = filepath
        csb.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES")

        Dim sql = "SELECT Continent FROM [Sheet1$]"
        Dim dt As New DataTable

        Using da As New OleDbDataAdapter(sql, csb.ConnectionString)
            da.Fill(dt)
        End Using

        ComboBox1.DataSource = dt
        ComboBox1.DisplayMember = dt.Columns(0).ColumnName

    End Sub

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

    End Sub

End Class

获得这样的组合框:

【讨论】:

    【解决方案3】:

    在编写代码之前首先要检查的是数据库和 excel 之间的兼容性。如果您使用的是 32 位 excel 版本,您将永远无法查询 64 位数据库。

    【讨论】:

    • 感谢我设法解决了这个问题,但我已经写了这个 sql 语句 ________ dt = GetDatafromExcelsheet("C:\Users\Nour\Desktop\projects\grade10\grade10\atlas.xlsx", "从 [Sheet1$] 中选择国家,其中大陆 = '" & ComboBox1.SelectedValue & "' ")
    • 我收到此错误消息 _____ System.InvalidCastException HResult=0x80004002 Message=Operator '&' is not defined for string "select country from [Sheet1$] wh" 并键入 'DataRowView'。跨度>
    【解决方案4】:

    从简单的事情开始,然后再做更复杂的事情。

    Imports Excel = Microsoft.Office.Interop.Excel
    Public Class Form1
        Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
    
            Dim xlApp As Excel.Application
            Dim xlWorkBook As Excel.Workbook
            Dim xlWorkSheet As Excel.Worksheet
    
            xlApp = New Excel.ApplicationClass
            xlWorkBook = xlApp.Workbooks.Open("c:\test1.xlsx")
            xlWorkSheet = xlWorkBook.Worksheets("sheet1")
            'display the cells value B2
            MsgBox(xlWorkSheet.Cells(2, 2).value)
            'edit the cell with new value
            xlWorkSheet.Cells(2, 2) = "http://vb.net-informations.com"
            xlWorkBook.Close()
            xlApp.Quit()
    
            releaseObject(xlApp)
            releaseObject(xlWorkBook)
            releaseObject(xlWorkSheet)
    
        End Sub
    
        Private Sub releaseObject(ByVal obj As Object)
            Try
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
                obj = Nothing
            Catch ex As Exception
                obj = Nothing
            Finally
                GC.Collect()
            End Try
        End Sub
    
    End Class
    

    完成这项工作,然后添加一个 ComboBox 对象。

    http://vb.net-informations.com/excel-2007/vb.net_excel_2007_open_file.htm

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-13
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      • 1970-01-01
      相关资源
      最近更新 更多