如何将excel文件导入mysql

时间:2018-02-10 18:41:28

标签: mysql excel vb.net

这是我得到的代码,只导入excel到datagridview。如何使用vb.net将excel导入mysql数据库?

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    OpenFileDialog1.ShowDialog()
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Try

        Dim MyConnection As System.Data.OleDb.OleDbConnection
        Dim dataSet 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=" + TextBox1.Text + ";Extended Properties=Excel 12.0;")
        MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)

        dataSet = New System.Data.DataSet
        MyCommand.Fill(dataSet)
        DataGridView1.DataSource = dataSet.Tables(0)

        MyConnection.Close()
    Catch ex As Exception
        MsgBox(ex.Message.ToString)
    End Try
End Sub

Private Sub OpenFileDialog1_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
    TextBox1.Text = OpenFileDialog1.FileName
End Sub

1 个答案:

答案 0 :(得分:0)

无论您使用VB还是其他语言。

  • 读取您的文件,然后循环
  • 您只需要将Excel column_title转换为包含(column1, column2, column3, ...)

  • 之类的字符串
  • 然后每个excel行连接values_variable:

(value1, value2, value3, ...), 
(value1, value2, value3, ...),
(value1, value2, value3, ...)
  • 因此,您只需要在循环结束时创建一个INSERT查询:
  

INSERT INTO table_name(column1,column2,column3,...)VALUES   (value1,value2,value3,...),(value1,value2,value3,...),   (value1,value2,value3,...),...;