VB .NET把Excel中的数据导入SQL SERVER数据库

其实不算原创,论坛里有人发的,我正好项目写到这里,缺的语句较多,无法运行,我补充了一下,可以简单的运行了,测试了一下,速度还不错。

VS2015可用,自己添加窗体和控件吧,只需要一个OpenFileDialog和Button,默认文件中带有字段名。

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.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;database=自己的数据库;user id=sa;password=密码"
                Dim conn As SqlClient.SqlConnection = New SqlClient.SqlConnection(CnnStr)
                conn.Open()
                Dim myCmd As SqlClient.SqlCommand
                Dim i As Integer
                For i = 0 To ds.Tables(0).Rows.Count - 1 Step i + 1
                    '根据自己的字段添加
                    strSql = "insert into 登录表 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 + "')"
                    Application.DoEvents()                   
                    myCmd = New SqlClient.SqlCommand(strSql, conn)
                    myCmd.ExecuteNonQuery()                   
                Next
                MsgBox("导入保存成功!", 48, "提示")
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
  • 4
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值