Import Data dari Excel ke MySQL dengan Visual Studio (VB .NET) 2010 |
Sudah membuat tabel di database MySQL.
Sudah menyiapkan file Excel yang akan diimpor.
Pastikan nama kolom di Excel dan MySQL sama.
(Asumsi) Sudah paham tentang dasar-dasar Visual Studio (VB.NET) 2010 & MySQL
Contoh:
Saya menyediakan 4 kolom di tabel database MySQL, seperti di bawah ini:
tabel MySQL |
Langkah-langkah:
1. Buat sebuah form (FrmImportPegawai) dengan komposisi:
1 buah TextBox = TextBox1
1 buah ListBox = ListBox1
1 buah GroupBox = GroupBox1, text: Data Excel **Optional
4 buah Button = btnBrowse, btnImport, btnBatal, btnKeluar
1 buah DataGridView = DataGridView1
2. Atur tampilan seperti di bawah ini atau sesuai dengan kebutuhan.
form import |
3. Drag OpenFileDialog dari ToolBox dan drop di form yang sudah dibuat.
4. Import Class yang digunakan dengan code:
Imports System.Windows.Forms
Imports System.Drawing Imports
System.Data.OleDb
Imports MySql.Data.MySqlClient
Imports MySql.Data.MySqlClient.MySqlDataReader
Imports System.Drawing Imports
System.Data.OleDb
Imports MySql.Data.MySqlClient
Imports MySql.Data.MySqlClient.MySqlDataReader
5. Deklarasikan Object data yang digunakan seperti di bawah ini:
Dim tblImport As DataTable
Dim conn As New MySqlConnection
Dim strConn As String = "server=localhost; database=namadatabasemu; uid=root; password=;"
Dim conn As New MySqlConnection
Dim strConn As String = "server=localhost; database=namadatabasemu; uid=root; password=;"
6. Event Form_Load seperti di bawah ini
Private Sub FrmImportPegawai_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
conn.ConnectionString = strConn
End Sub
conn.ConnectionString = strConn
End Sub
7. Klik dua kali tombol Browse dan isi dengan code hingga seperti di bawah ini:
Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
With OpenFileDialog1
.FileName = String.Empty
.InitialDirectory = "C:\"
.Title = "Pilih File Excel"
.Filter = "Excel|*.xls;*.xlsx"
End With
Dim result As DialogResult = OpenFileDialog1.ShowDialog()
If result = Windows.Forms.DialogResult.OK Then
Try
TextBox1.Text = OpenFileDialog1.FileName
AmbilNamaSheet(TextBox1.Text)
Catch ex As Exception
MsgBox("Error : " & ex.Message)
End Try
End If
End Sub
With OpenFileDialog1
.FileName = String.Empty
.InitialDirectory = "C:\"
.Title = "Pilih File Excel"
.Filter = "Excel|*.xls;*.xlsx"
End With
Dim result As DialogResult = OpenFileDialog1.ShowDialog()
If result = Windows.Forms.DialogResult.OK Then
Try
TextBox1.Text = OpenFileDialog1.FileName
AmbilNamaSheet(TextBox1.Text)
Catch ex As Exception
MsgBox("Error : " & ex.Message)
End Try
End If
End Sub
8. Buat prosedur dengan nama AmbilNamaSheet dengan code di bawah ini:
Public Sub AmbilNamaSheet (ByVal FileName As String)
Dim sConn As String
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & FileName & ";Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
Dim conn As New OleDbConnection(sConn)
conn.Open()
Dim dtSheets As DataTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim drSheet As DataRow
ListBox1.Items.Clear()
For Each drSheet In dtSheets.Rows
ListBox1.Items.Add(drSheet("TABLE_NAME").ToString())
Next
TampilEcxelKeGrid(FileName, ListBox1.Items(0).ToString)
conn.Close()
End Sub
Dim sConn As String
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & FileName & ";Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
Dim conn As New OleDbConnection(sConn)
conn.Open()
Dim dtSheets As DataTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim drSheet As DataRow
ListBox1.Items.Clear()
For Each drSheet In dtSheets.Rows
ListBox1.Items.Add(drSheet("TABLE_NAME").ToString())
Next
TampilEcxelKeGrid(FileName, ListBox1.Items(0).ToString)
conn.Close()
End Sub
9. Buat prosedur dengan nama TampilExcelKeGrid dengan code di bawah ini:
'Untuk menampilkan data sheet di grid
Public Sub TampilEcxelKeGrid (ByVal FileName As String, ByVal SheetName As String)
Dim exConn As OleDbConnection 'MySqlConnection
Dim dt As DataSet
Dim cmd As OleDbDataAdapter 'MySqlDataAdapter
Dim sConn As String
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & FileName & ";Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
'exConn = New MySql.Data.MySqlClient.MySqlConnection(sConn)
exConn = New System.Data.OleDb.OleDbConnection(sConn)
'cmd = New MySql.Data.MySqlClient.MySqlDataAdapter("select * from [" & SheetName & "]", exConn)
cmd = New System.Data.OleDb.OleDbDataAdapter("select * from [" & SheetName & "]", exConn)
cmd.TableMappings.Add("Table", SheetName)
dt = New System.Data.DataSet
cmd.Fill(dt)
tblImport = dt.Tables(0)
DataGridView1.DataSource = tblImport
FormatGrid()
exConn.Close()
End Sub
Public Sub TampilEcxelKeGrid (ByVal FileName As String, ByVal SheetName As String)
Dim exConn As OleDbConnection 'MySqlConnection
Dim dt As DataSet
Dim cmd As OleDbDataAdapter 'MySqlDataAdapter
Dim sConn As String
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & FileName & ";Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
'exConn = New MySql.Data.MySqlClient.MySqlConnection(sConn)
exConn = New System.Data.OleDb.OleDbConnection(sConn)
'cmd = New MySql.Data.MySqlClient.MySqlDataAdapter("select * from [" & SheetName & "]", exConn)
cmd = New System.Data.OleDb.OleDbDataAdapter("select * from [" & SheetName & "]", exConn)
cmd.TableMappings.Add("Table", SheetName)
dt = New System.Data.DataSet
cmd.Fill(dt)
tblImport = dt.Tables(0)
DataGridView1.DataSource = tblImport
FormatGrid()
exConn.Close()
End Sub
10. Buat prosedur dengan nama Masuk dengan code di bawah ini:
Sub Masuk(ByVal strIDPegawai As String, ByVal strNama As String, ByVal strNIP As String, ByVal strUnitJenjang As String)
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim myData As New DataTable
Dim SQL As String
Try
If conn.State = ConnectionState.Closed Then conn.Open()
SQL = "INSERT IGNORE INTO databasepegawai (IDPegawai, Nama, NIP, UnitJenjang) VALUES " & "('" & strIDPegawai & "', '" & strNama & "', '" & strNIP & "', '" & strUnitJenjang & "')"
myCommand.Connection = conn
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
MsgBox("Data baru telah tersimpan", MsgBoxStyle.Information, "Informasi")
conn.Close()
Catch myerror As MySqlException
MessageBox.Show("Error: " & myerror.Message)
Finally
conn.Dispose()
End Try
End Sub
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim myData As New DataTable
Dim SQL As String
Try
If conn.State = ConnectionState.Closed Then conn.Open()
SQL = "INSERT IGNORE INTO databasepegawai (IDPegawai, Nama, NIP, UnitJenjang) VALUES " & "('" & strIDPegawai & "', '" & strNama & "', '" & strNIP & "', '" & strUnitJenjang & "')"
myCommand.Connection = conn
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
MsgBox("Data baru telah tersimpan", MsgBoxStyle.Information, "Informasi")
conn.Close()
Catch myerror As MySqlException
MessageBox.Show("Error: " & myerror.Message)
Finally
conn.Dispose()
End Try
End Sub
11. Klik dua kali tombol Import dan isi dengan code hingga seperti di bawah ini:
Private Sub btnImport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImport.Click
For i As Integer = 0 To tblImport.Rows.Count - 1
Masuk(tblImport.Rows(i).Item(0).ToString, _
tblImport.Rows(i).Item(1).ToString, _
tblImport.Rows(i).Item(2).ToString, _
tblImport.Rows(i).Item(3).ToString, _
tblImport.Rows(i).Item(4).ToString)
Next
MsgBox("Proses Import Selesai!", MsgBoxStyle.Information, "Informasi")
Awal()
End Sub
For i As Integer = 0 To tblImport.Rows.Count - 1
Masuk(tblImport.Rows(i).Item(0).ToString, _
tblImport.Rows(i).Item(1).ToString, _
tblImport.Rows(i).Item(2).ToString, _
tblImport.Rows(i).Item(3).ToString, _
tblImport.Rows(i).Item(4).ToString)
Next
MsgBox("Proses Import Selesai!", MsgBoxStyle.Information, "Informasi")
Awal()
End Sub
12. Klik dua kali tombol Batal dan isi dengan code hingga seperti di bawah ini:
Private Sub btnBatal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBatal.Click
DataGridView1.DataSource = NothingDataGridView1.Rows.Clear()
ListBox1.Items.Clear()
TextBox1.Text = String.Empty
End Sub
13. Klik dua kali tombol Keluar dan isi dengan code hingga seperti di bawah ini:
Private Sub btnKeluar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnKeluar.Click
Me.Close()
End Sub
Me.Close()
End Sub
14. Klik dua kali TextBox1 dan isi dengan code di bawah ini:
btnImport.Enabled = (Len(TextBox1.Text) > 0)
15. Klik dua kali ListBox1 dan isi dengan code di bawah ini:
TampilEcxelKeGrid(TextBox1.Text, ListBox1.SelectedItem.ToString)
16. Tekan F5 dan lihat hasilnya
hasil import |
Sumber:
Irsan, Rani. VB.NET MySQL: Import Data dari Excel - Part 1. ENCHANTMENT OF HIDDEN BEAUTY: PESONA KECANTIKAN TERSEMBUNYI. 22 April 2015. 29 September 2017. http://rani-irsan.blogspot.co.id/2015/04/vbnet-mysql-import-data-dari-excel-part.html
4 komentar
Write komentarterimaksih, saya telah menggunakan code source dan berhasil, namun ada kendala sbb :
Replysaat import data dari excel baru/blm terdapat database mysql = lancar
saat import data dari excel tetapi sudah terdapat data tersebut pasti terhenti karena data yg termasuk primery key pasti baca kalau data sudah ada, klo pakai ignor memang lewat saja.
permasalahannya walau data yang saya import sama tetapi ada kolong yang harus saya edit / update value-nya.
contoh kolom unitjenjang value-nya ABC saat saya import data harusnya diedit menjadi DEF dst.
mohon pencerahan, terimakasih salam dari papua
Kalau kasusnya seperti itu, coba ubah saja kode di bagian "Sub Masuk" (langkah no 10).
Replyubah kode misal: jika data sudah ada lakukan update, kalau data belum ada maka insert.
intinya seperti itu.
Tks atas sharingny. saya gagal menggunakan nya. err. nya di bagian TABLE_NAME. apa yang mesti diisi di table name ini ?
Replyawal itu apa? formatgrid itu apa? dan terlalu banyak submasuk karena tidak di jelaskan
ReplyEmoticonEmoticon