如何使用vb.net中excel表中的数据更新sql表

时间:2015-11-19 16:29:42

标签: sql vb.net excel sql-update

我在使用excel表更新sql表时遇到问题。事实是,我正在开发这个小项目,用户可以首先通过单击vb.net应用程序中的按钮导出或打印带有StudentNumber,SubjectID,ClassScore,ExamScore的课程列表,然后编辑工作表。填写ClassScore和ExamScore,然后通过vb.net将工作表上传回sql。 问题是如何检查当前的StudentNumber或行是否存在于sql表中,然后更新表,否则插入一个新行。 这是我使用SQLBulk Copy的代码,只需在vb.net中更新sql表

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ofd As New OpenFileDialog

    If ofd.ShowDialog() <> System.Windows.Forms.DialogResult.OK Then Exit Sub
    ' Dim dgv As System.Windows.Forms.DataGridView
    With ofd
        .Filter = "Excel files(*.xls)|*.xls|All files (*.*)|*.*"
        .FilterIndex = 1
        .Title = "Import data from Excel file"
    End With
    Dim nme As String = ofd.FileName
          Import(nme, dgv)

End Sub
Public Shared Function Import(ByVal FileName As String, ByVal dgv As DataGridView) As Boolean
    Dim MyConnection As System.Data.OleDb.OleDbConnection
    Dim DtSet As System.Data.DataSet
    Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
    MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties=Excel 12.0 Xml;")
    'MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\vb.net-informations.xls';Extended Properties=Excel 8.0;")
    MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
    MyCommand.TableMappings.Add("Table", "Scores")
    DtSet = New System.Data.DataSet
    MyCommand.Fill(DtSet)
    dgv.DataSource = DtSet.Tables(0)
    MyConnection.Close()


    Dim expr As String = "SELECT * FROM [Sheet1$]"


    Dim SQLconn As New SqlConnection()
    Dim ConnString As String = "Data Source=xxxx-PC;Initial Catalog=TryExcel;Persist Security Info=True;User ID=xx;Password=xxxx"
    Dim objCmdSelect As OleDbCommand = New OleDbCommand(expr, MyConnection)
    Dim objDR As OleDbDataReader

    SQLconn.ConnectionString = ConnString

    Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(ConnString)
        bulkCopy.DestinationTableName = "Scores"

        MyConnection.Open()
        objDR = objCmdSelect.ExecuteReader
        bulkCopy.WriteToServer(objDR)
        objDR.Close()
        SQLconn.Close()

    End Using
    Return True
End Function

Private Shared Function safefilename() As String
    Throw New NotImplementedException
End Function

1 个答案:

答案 0 :(得分:0)

Private Sub Upload_Workbook()

        Dim t As New Thread(New ThreadStart(Sub()
                                                dt = New DataTable

                                                dt = New DataTable("Table_Name")
                                                dt.Columns.Add("Column_1")
                                                dt.Columns.Add("Column_2)
                                                dt.Columns.Add("Column_3")
                                                dt.Columns.Add("Column_4")
                                                dt.Columns.Add("Column_5")
                                                dt.Columns.Add("Column_6")
                                                dt.Columns.Add("Column_7")

                                                ds = New DataSet
                                                ds.Tables.Add(dt)

                                                Dim i As Integer

                                                For i = 2 To (Cells(1, 11).Text)

                                                    dr = dt.NewRow
                                                    dr(0) = Cells(i, 1).Text
                                                    dr(1) = Cells(i, 2).Text
                                                    dr(2) = Cells(i, 3).Text
                                                    dr(3) = Cells(i, 4).Text
                                                    dr(4) = Cells(i, 5).Text
                                                    dr(5) = Cells(i, 6).Text
                                                    dr(6) = Cells(i, 7).Text

                                                    dt.Rows.Add(dr)
                                                Next i

                                                trans = con.BeginTransaction
                                                Try
                                                    Dim row As Integer

                                                    While (row < dt.Rows.Count)

                                                        Dim cmd As New SqlCommand("Sheet1_Upload", con, trans)

                                                        cmd.CommandType = CommandType.StoredProcedure

                                                        cmd.Parameters.AddWithValue("Column_1", dt.Rows(row).ItemArray(0))
                                                        cmd.Parameters.AddWithValue("Column_2", dt.Rows(row).ItemArray(1))
                                                        cmd.Parameters.AddWithValue("Column_3", dt.Rows(row).ItemArray(2))
                                                        cmd.Parameters.AddWithValue("Column_4", dt.Rows(row).ItemArray(3))
                                                        cmd.Parameters.AddWithValue("Column_5", dt.Rows(row).ItemArray(4))
                                                        cmd.Parameters.AddWithValue("Column_6", dt.Rows(row).ItemArray(5))
                                                        cmd.Parameters.AddWithValue("Column_7", dt.Rows(row).ItemArray(6))
                                                        cmd.ExecuteNonQuery()

                                                        row = row + 1

                                                    End While

                                                    trans.Commit()

                                                Catch ex As Exception
                                                    MsgBox(ex.Message)
                                                    trans.Rollback()
                                                End Try

                                            End Sub))

        t.Start()
End Sub

''''''SQL存储过程'''''''

创建过程Sheet1_Upload(@ Column_1 varchar(50),@ Column_2 varchar(50),@ Column_3 varchar(50),@ Column_4 varchar(50),@ Column_5 varchar(50),@ Column_6 varchar(50)) 如 开始

插入INTO Table_Name(Column_1,Column_2,Column_3,Column_4,Column_5,Column_6)值(@ Column_1,@ Column_2,@ Column_3,@ Column_4,@ Column_5,@ Column_6) 端

  

请在Visual Basic上创建此项目&gt; Office / Share Point&gt; Excel 2013 Workbook。File Path Image   然后使用另一个程序打开工作簿。

    oXL = CreateObject("Excel.Application")
    oXL.Visible = False
    oWB = oXL.Workbooks.Open("D:\workbook.xlsm")
    oWB.Activate()
    oWB.RunAutoMacros(Excel.XlRunAutoMacro.xlAutoOpen)
  

在VB.net中使用excel Auto_Open宏和工作表更改事件。