簡體   English   中英

從 Excel 工作表讀取

[英]Reading from Excel sheet

我編寫了下面的代碼來從 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()

試試這個代碼

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

要讀取 xlsx 文件而不是 xls 文件,您將需要ACE 提供程序而不是 JET 提供程序。 您需要添加擴展屬性“HDR=Yes”以告訴它有一個標題行。

工作表的名稱后面需要一個$

要組成連接字符串,您可以使用 connectionstringbuilder - 它將負責添加任何引號或從各個部分創建有效連接字符串所需的任何內容。

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

獲得這樣的組合框:

在此處輸入圖片說明

在進入代碼之前首先要檢查數據庫和 excel 之間的兼容性。 如果您使用的是 32 位 excel 版本,您將永遠無法查詢 64 位數據庫。

從簡單的事情開始,然后再做更復雜的事情。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM