簡體   English   中英

將 Excel / Array 數據導入數據庫

[英]Import Excel / Array data to a database

我正在用 VB 編寫代碼,以便擁有一個包含更新員工信息的公司網站。 我的目標是: 從 Excel 文件中收集某些數據 將數據保存到 2D 數組 將數組數據更新到網站可訪問的數據庫中 創建網站並輕松使用數據庫數據(以便網站可以輕松編輯)

我遇到了兩個問題:

  1. 我使用 Try & Catch 來解決空白單元格上的 Nullreference 異常 - 讀取帶有大量空白單元格的列時,腳本非常慢
  2. 我不知道如何正確地將收集到的數據放入數據庫(sql accces / 不重要)

目前我們使用帶有宏和 Excel VB 的 Excel 文件來生成站點(將輸出直接寫入 html 文件 - 所以它非常靜態..)

由於私人員工信息,我無法共享 excel 文件,但我共享了代碼(我知道,這有點草率,因為這是我第一次使用 excel 數據,所以我做了很多“重新編輯”我的代碼)

(最后我添加了一個 listbox1 更新來驗證最后一條記錄是否正確添加)

如果有更好的解決方案(直接從excel導入到數據庫),請分享:)

提前謝謝大家!

Imports Excel = Microsoft.Office.Interop.Excel

Public Class WieiswieForm
    Private Sub WieiswieForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub

    Public Sub ChoseFile_Click(sender As Object, e As EventArgs) Handles ChoseFile.Click
        OpenFileDialog1.Filter = "Excel | *.xlsm"
        Dim result As DialogResult = OpenFileDialog1.ShowDialog()
        FileTextBox.Text = OpenFileDialog1.FileName
        UpdateButton.Enabled = True

    End Sub


    Public Sub UpdateButton_Click(sender As Object, e As EventArgs) Handles UpdateButton.Click

        UpdateButton.Enabled = False

        ListBox1.Items.Add(DateAndTime.Now.ToString & ": starten...")

        Dim Filepath As String = OpenFileDialog1.FileName
        Dim Afdeling_cell As String = "C"
        Dim Functie_cell As String = "D"
        Dim Naam_cell As String = "E"
        Dim Organistaie_cell As String = "N"
        Dim Badgenummer_cell As String = "R"
        Dim Draagbaar_cell As String = "Y"
        Dim VastNummer_cell As String = "X"
        Dim GSM_cell As String = "AB"
        Dim Werkrooster_cell As String = "AE"
        Dim Normtijd_cell As String = "AF"
        Dim Afwezigheid_cell As String = "AG"
        Dim Vestiging_cell As String = "AI"

        Dim Cell_index(11) As String
        Cell_index(0) = Naam_cell
        Cell_index(1) = Afdeling_cell
        Cell_index(2) = Functie_cell
        Cell_index(3) = Organistaie_cell
        Cell_index(4) = Vestiging_cell
        Cell_index(5) = Werkrooster_cell
        Cell_index(6) = VastNummer_cell
        Cell_index(7) = Draagbaar_cell
        Cell_index(8) = GSM_cell
        Cell_index(9) = Afwezigheid_cell
        Cell_index(10) = Badgenummer_cell
        Cell_index(11) = Normtijd_cell


        If Filepath = "" Then
            MsgBox("Geen bestand geselecteerd..")

        Else
            ListBox1.Items.Add(DateAndTime.Now.ToString & ": Excel bestand openen...")
            Dim range As Excel.Range
            Dim file As System.IO.StreamWriter


            ' Get the Excel application object.
            Dim excel_app As New Excel.ApplicationClass()

            ' Make Excel visible (optional).
            excel_app.Visible = False

            ' Open the workbook read-only.
            Dim workbook As Excel.Workbook =
        excel_app.Workbooks.Open(
        Filename:=Filepath, ReadOnly:=True)

            ' Get the first worksheet.
            Dim sheet As Excel.Worksheet =
        DirectCast(workbook.Sheets(1), Excel.Worksheet)

            ' Get the number of rows (to avoid an index out-of-range)
            Dim LastRow As Integer
            LastRow = sheet.UsedRange.Rows.Count

            '################## SUB START

            'Create the data array
            ListBox1.Items.Add(DateAndTime.Now.ToString & ": data verzamel object maken...")
            Dim DataArray(11, LastRow - 1) As String

            'Create the object to retrieve the data from the range 
            Dim saRet(,) As Object
            Dim iRows As Long
            Dim iCols As Long

            ' #########################################################################################

            ' Start the data colletion loop
            Dim arrayindex1 As Integer = 0
            Dim arrayindex2 As Integer = 0
            Dim c As Integer = 0

            ProgressBar1.Value = 10

            'Namen oplijsten :
            ListBox1.Items.Add(DateAndTime.Now.ToString & ": namen ophalen...")
            MaakArray(arrayindex1, arrayindex2, c, sheet, LastRow, range, saRet, iRows, iCols, Cell_index, DataArray)

            'Afdeling ophalen
            ListBox1.Items.Add(DateAndTime.Now.ToString & ": afdelingen ophalen...")
            ProgressBar1.Value = 20
            c = c + 1 '1
            arrayindex1 = arrayindex1 + 1
            arrayindex2 = 0
            MaakArray(arrayindex1, arrayindex2, c, sheet, LastRow, range, saRet, iRows, iCols, Cell_index, DataArray)

            'Functie binnen de afdeling : 
            ListBox1.Items.Add(DateAndTime.Now.ToString & ": functies ophalen...")
            ProgressBar1.Value = 30
            c = c + 1 '2
            arrayindex1 = arrayindex1 + 1
            arrayindex2 = 0
            MaakArray(arrayindex1, arrayindex2, c, sheet, LastRow, range, saRet, iRows, iCols, Cell_index, DataArray)

            'Organisatie ophalen

            ListBox1.Items.Add(DateAndTime.Now.ToString & ": organisaties ophalen...")
            ProgressBar1.Value = 40
            c = c + 1 '3
            arrayindex1 = arrayindex1 + 1
            arrayindex2 = 0
            MaakArray(arrayindex1, arrayindex2, c, sheet, LastRow, range, saRet, iRows, iCols, Cell_index, DataArray)

            'Vestiging ophalen

            ListBox1.Items.Add(DateAndTime.Now.ToString & ": vestigingen ophalen...")
            ProgressBar1.Value = 50
            c = c + 1 '4
            arrayindex1 = arrayindex1 + 1
            arrayindex2 = 0
            MaakArray(arrayindex1, arrayindex2, c, sheet, LastRow, range, saRet, iRows, iCols, Cell_index, DataArray)

            'werkrooster ophalen

            ListBox1.Items.Add(DateAndTime.Now.ToString & ": werkroosters ophalen...")
            ProgressBar1.Value = 60
            c = c + 1 '5
            arrayindex1 = arrayindex1 + 1
            arrayindex2 = 0
            MaakArray(arrayindex1, arrayindex2, c, sheet, LastRow, range, saRet, iRows, iCols, Cell_index, DataArray)

            'vastnummer ophalen

            ListBox1.Items.Add(DateAndTime.Now.ToString & ": vaste telefoonnummers ophalen...")
            ProgressBar1.Value = 70
            c = c + 1 '6
            arrayindex1 = arrayindex1 + 1
            arrayindex2 = 0
            MaakArray(arrayindex1, arrayindex2, c, sheet, LastRow, range, saRet, iRows, iCols, Cell_index, DataArray)

            'draagpaar ophalen

            ListBox1.Items.Add(DateAndTime.Now.ToString & ": draagbarenummers ophalen...")
            ProgressBar1.Value = 75
            c = c + 1 '7
            arrayindex1 = arrayindex1 + 1
            arrayindex2 = 0
            MaakArray(arrayindex1, arrayindex2, c, sheet, LastRow, range, saRet, iRows, iCols, Cell_index, DataArray)

            'GSM ophalen

            ListBox1.Items.Add(DateAndTime.Now.ToString & ": GSM nummers ophalen...")
            ProgressBar1.Value = 80
            c = c + 1 '8
            arrayindex1 = arrayindex1 + 1
            arrayindex2 = 0
            MaakArray(arrayindex1, arrayindex2, c, sheet, LastRow, range, saRet, iRows, iCols, Cell_index, DataArray)

            'Afwezigheden ophalen
            ListBox1.Items.Add(DateAndTime.Now.ToString & ": Afwezigheden nummer ophalen...")
            ProgressBar1.Value = 85
            c = c + 1 '9
            arrayindex1 = arrayindex1 + 1
            arrayindex2 = 0
            MaakArray(arrayindex1, arrayindex2, c, sheet, LastRow, range, saRet, iRows, iCols, Cell_index, DataArray)

            'Badgenummers ophalen
            ListBox1.Items.Add(DateAndTime.Now.ToString & ": badgenummers ophalen...")
            ProgressBar1.Value = 90
            c = c + 1 '10
            arrayindex1 = arrayindex1 + 1
            arrayindex2 = 0
            MaakArray(arrayindex1, arrayindex2, c, sheet, LastRow, range, saRet, iRows, iCols, Cell_index, DataArray)

            'Normtijd ophalen
            ListBox1.Items.Add(DateAndTime.Now.ToString & ": Normtijd ophalen...")
            ProgressBar1.Value = 95
            c = c + 1 '10
            arrayindex1 = arrayindex1 + 1
            arrayindex2 = 0
            MaakArray(arrayindex1, arrayindex2, c, sheet, LastRow, range, saRet, iRows, iCols, Cell_index, DataArray)



            ' Save the changes and close the workbook.
            workbook.Close(SaveChanges:=False)

            ' Close the Excel server.
            excel_app.Quit()

            ProgressBar1.Value = 100

            ListBox1.Items.Add(DateAndTime.Now.ToString & ": Bestand opgeladen!")
            ListBox1.Items.Add(DataArray(0, 501) & " " & DataArray(1, 501) & " " & DataArray(2, 501) & " " & DataArray(3, 501) & DataArray(4, 501) & DataArray(5, 501) & DataArray(6, 501) & DataArray(7, 501) & DataArray(8, 501))
            UpdateButton.Enabled = True
            MsgBox((DataArray(0, 501) & " " & DataArray(1, 501) & " " & DataArray(2, 501) & " " & DataArray(3, 501) & " " & DataArray(4, 501) & " " & DataArray(5, 501) & " " & DataArray(6, 501) & " " & DataArray(7, 501) & " " & DataArray(8, 501) & " " & DataArray(9, 501) & " " & DataArray(10, 501)))
        End If
    End Sub




Sub MaakArray(arrayindex1 As Integer, arrayindex2 As Integer, c As Integer, sheet As Excel.Worksheet, LastRow As Integer, range As Excel.Range, saret As Object, iRows As Long, iCols As Long, Cell_index() As String, ByRef DataArray(,) As String)


    Dim LoopTime As Integer = 0
    Do Until LoopTime = 11

        'Get a range of data.
        range = sheet.Range(Cell_index(c) & "2", Cell_index(c) & LastRow)

        'Retrieve the data from the range.
        saret = range.Value

        'Determine the dimensions of the array.
        iRows = saret.GetUpperBound(0)
        iCols = saret.GetUpperBound(1)

        'Build a string that contains the data of the array.
        Dim valueString As String
        'valueString = "" + vbCrLf



        Dim rowCounter As Long
        Dim colCounter As Long
        Dim i As Integer
        For rowCounter = 1 To iRows
            For colCounter = 1 To iCols


                'Write the next value into the string.

                Try
                    valueString = saret(rowCounter, colCounter).ToString()
                    'If String.IsNullOrEmpty(valueString) Then
                    'valueString = ""
                    ' End If
                Catch
                    valueString = ""

                End Try



                DataArray(arrayindex1, arrayindex2) = valueString


                If arrayindex2 = LastRow - 1 Then
                    arrayindex2 = arrayindex2
                Else
                    arrayindex2 = arrayindex2 + 1
                End If


                ProgressBar1.Value = ProgressBar1.Value + 1 / 10

            Next colCounter

        Next rowCounter
        LoopTime = LoopTime + 1

    Loop


    '#########################################################################


    End Sub
End Class

只是為了咧嘴笑,請嘗試以下操作,看看您會得到什么。 您可能需要將連接字符串中的 HDR=YES 調整為 HDR=NO。 將 DataGridView 添加到您的表單,以便您可以查看結果。 這至少會向您介紹 Excel 的數據提供程序。 擁有 DataTable 后,如果您有主鍵,則可以更新數據庫。

添加到文件頂部

導入 System.Data.OleDb

表單中的代碼

Private Sub btnLoadGrid_Click(sender As Object, e As EventArgs) Handles btnLoadGrid.Click
    Dim dt As New DataTable
    Dim strFileName As String = "Your file path"
    Dim strCon As String = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={strFileName};Extended Properties=""Excel 12.0;HDR=YES;"""
    Using cn = New OleDbConnection(strCon)
        Debug.Print(cboSheets.Text)
        Using cmd As New OleDbCommand($"Select * From [Sheet1$];", cn)
            cn.Open()
            Using dr As OleDbDataReader = cmd.ExecuteReader
                dt.Load(dr)
            End Using
        End Using
    End Using
    DataGridView1.DataSource = dt
End Sub

暫無
暫無

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

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