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