【VB.net】EXCEL数据导入至MYSQL


Imports System.Data
Imports Microsoft.SqlServer.Server
Imports MySql.Data.MySqlClient
Imports System.Data.OleDb
Imports Excel = Microsoft.Office.Interop.Excel

Public Class Form1

 Private Sub ToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 导入ToolStripMenuItem1.Click

        Try
            Dim fileName As String
            OpenFileDialog1.ShowDialog()
            fileName = OpenFileDialog1.FileName
            '建立EXCEL连接,读入数据,支持 Microsoft Excel 2010
            Dim strConn As String = "Provider= Microsoft.Ace.OleDb.12.0;Data Source='" & fileName & "';Extended Properties=Excel 12.0;"
            '建立EXCEL连接,读入数据,支持 Microsoft Excel 2003
            'Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & fileName & "';Extended Properties=Excel 8.0;"
            Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn)
            Dim ds As DataSet = New DataSet
            da.Fill(ds)
            Me.DataGridView1.DataSource = ds.Tables(0)
            If ds.Tables(0).Rows.Count > 0 Then
                Dim strSql As String
                Dim CnnStr As String = "Server=localhost;User ID=root;Password=;Database=emp;"
                Dim conn As MySqlConnection = New MySqlConnection(CnnStr)
                conn.Open()
                Dim myCmd As MySqlCommand
                Dim i As Integer
                For i = 0 To ds.Tables(0).Rows.Count - 1 Step i + 1
                    '根据自己的字段添加
                    strSql = "insert into test(empno,username,password,sex,sal,tel,hiredate,address,role)VALUES ('" + ds.Tables(0).Rows(i).Item(0).ToString + "','" +
                        ds.Tables(0).Rows(i).Item(1).ToString + "','" +
                        ds.Tables(0).Rows(i).Item(2).ToString + "','" +
                        ds.Tables(0).Rows(i).Item(3).ToString + "','" +
                        ds.Tables(0).Rows(i).Item(4).ToString + "','" +
                        ds.Tables(0).Rows(i).Item(5).ToString + "','" +
                        ds.Tables(0).Rows(i).Item(6).ToString + "','" +
                        ds.Tables(0).Rows(i).Item(7).ToString + "','" +
                        ds.Tables(0).Rows(i).Item(8).ToString + "')"

                    Application.DoEvents()
                    myCmd = New MySqlCommand(strSql, conn)
                    myCmd.ExecuteNonQuery()
                Next
                MsgBox("导入保存成功!", 48, "提示")
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
End Class

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值