Masih banyak yang bingung gimana sih masukkin data yang ada di excel ke SQL server, masa kita harus insert satu persatu data yang di excel ke SQL, iya kalo data nya cuma dikit, tapi gimana kalo ratusan atau ribuan?seperti migrasi data karyawan. Ini solusinya, ane coba kasih source code untuk import dari excel ke SQL server.
Button [...] digunakan untuk membuka file excel nya, berikut codingnya
setelah file excel dipilih maka combobox akan terisi dengan judul sheet file excel, pilih sheet yang akan diimport dan Button [LOAD] digunakan untuk menampilkan data sheet Excel ke MSFlexGrid, nah data yang tampil ini lah yang akan masuk ke SQL. Setelah data dimuat dalam Grid maka Button [LOAD] akan berubah menjadi [IMPORT]. Berikut source nya :Private Sub Command1_Click()Dim OFName As OPENFILENAMEDim XLS As ObjectDim WRK As ObjectDim SHT As ObjectOn Error GoTo exOFName.lStructSize = Len(OFName)'Set the parent windowOFName.hwndOwner = Me.hWnd'Set the application's instanceOFName.hInstance = App.hInstance'Select a filterOFName.lpstrFilter = "Excel Files (*.xls)" + Chr$(0) + "*.xls" + Chr$(0) + "All Files (*.*)" + Chr$(0) + "*.*" + Chr$(0)'create a buffer for the fileOFName.lpstrFile = Space$(254)'set the maximum length of a returned fileOFName.nMaxFile = 255'Create a buffer for the file titleOFName.lpstrFileTitle = Space$(254)'Set the maximum length of a returned file titleOFName.nMaxFileTitle = 255'Set the initial directoryOFName.lpstrInitialDir = "C:\"'Set the titleOFName.lpstrTitle = "Open XLS File"'No flagsOFName.flags = 0
'Show the 'Open File'-dialogIf GetOpenFileName(OFName) ThenText1.Text = Trim$(OFName.lpstrFile)Combo1.Clear'Create a new instance of ExcelSet XLS = CreateObject("Excel.Application")'Open the XLS file. The two parameters representes, UpdateLink = False and ReadOnly = True. These parameters have this setting to dont occur any error on broken links and allready opened XLS file.Set WRK = XLS.Workbooks.Open(Text1.Text, False, True)'Read all worksheets in xls fileFor Each SHT In WRK.Worksheets'Put the name of worksheet in comboCombo1.AddItem SHT.NameNext'Close the XLS file and dont saveWRK.Close False'Quit the MS ExcelXLS.Quit'Release variablesSet XLS = NothingSet WRK = NothingSet SHT = NothingElseMsgBox "Cancel was pressed"End IfExit Subex:MsgBox Err.DescriptionEnd Sub
On Error GoTo step_errorDim XLS As Object 'New Excel.ApplicationDim WRK As Object 'Excel.WorkbookDim SHT As Object 'Excel.WorksheetDim RNG As Object ' Excel.RangeDim ArrayCells() As VariantIf Command2.Caption = "LOAD" ThenIf Combo1.ListIndex <> -1 Then'Create a new instance of ExcelSet XLS = CreateObject("Excel.Application")'Open the XLS file. The two parameters representes, UpdateLink = False and ReadOnly = True. These parameters have this setting to dont occur any error on broken links and allready opened XLS file.Set WRK = XLS.Workbooks.Open(Text1.Text, False, True)'Set the SHT variable to selected worksheetSet SHT = WRK.Worksheets(Combo1.List(Combo1.ListIndex))'Get the used range of current worksheetSet RNG = SHT.UsedRange'Change the dimensions of array to fit the used range of worksheetReDim ArrayCells(1 To RNG.Rows.Count, 1 To RNG.Columns.Count)'Transfer values of the used range to new array' If Option1.Value ThenArrayCells = RNG.Value' ElseIf Option2.Value Then' ArrayCells = RNG.Formula' End If'Close worksheetWRK.Close False'Quit the MS ExcelXLS.Quit'Release variablesSet XLS = NothingSet WRK = NothingSet SHT = NothingSet RNG = Nothing'Configure the flexgrid to display dataMSFlexGrid1.Redraw = FalseMSFlexGrid1.FixedCols = 0MSFlexGrid1.FixedRows = 0MSFlexGrid1.Rows = UBound(ArrayCells, 1)MSFlexGrid1.Cols = UBound(ArrayCells, 2)For r = 0 To UBound(ArrayCells, 1) - 1For c = 0 To UBound(ArrayCells, 2) - 1MSFlexGrid1.TextMatrix(r, c) = CStr(ArrayCells(r + 1, c + 1))NextNextMSFlexGrid1.Redraw = TrueElseMsgBox "DATA BELOM ADA OM!", vbCritical, "ERROR"Combo1.SetFocusEnd IfMSFlexGrid1.AllowUserResizing = flexResizeBothCommand2.Caption = "IMPORT"Exit Substep_error:MsgBox Err.Number & " - " & Err.DescriptionResume Next
ElseDim rs As New ADODB.RecordsetDim i As Double'BUAT KONEKSI KE DATABASESet cn = New ADODB.Connectioncn.CursorLocation = adUseClientstrkon = "Provider=SQLOLEDB.1;Password=123;Persist Security Info=True;User ID=sa;Data Source=isi server sql ente disini;Initial Catalog=isi nama database ente"cn.ConnectionString = strkoncn.OpenWith MSFlexGrid1 'sesuaikan nama flexgrid ente
For i = 1 To MSFlexGrid1.Rows - 1
rs.Open "select * from tblhrtambahan where fperiode = '" & .TextMatrix(i, 0) & "'", cn, adOpenDynamic, adLockOptimistic ' masukkan query table yang akan menerima data excel
If rs.EOF = True Then 'sesuaikan logika dengan kebutuhan enters.AddNew 'insert data baru ke table yang ente query sebelumnyars!fperiode = .TextMatrix(i, 0) 'sebutkan field yang akan ente masukkan datanya (.textMatrix itu adalah data excel yang berada dalam grid ente, i disini adalah perolehan hasil looping untuk baris, sedangkan 0 nya adalah kolom pertama di grid)rs!fnik = .TextMatrix(i, 1)rs!fothercode = .TextMatrix(i, 2)rs!fotherjumlah = .TextMatrix(i, 3)rs!fkettambahan = .TextMatrix(i, 4)
rs.Update 'mengisi field table yang ente query sebelumnya dengan data di grid yang dijanarkan code di atas ini
ElseMsgBox ("Periode " & .TextMatrix(1, 0) & " sudah ada "), vbCritical, "ERROR" 'sesuaikan logika dengan kebutuhan enteEnd Ifrs.Close 'menutup recordset yang dipakaiNext i 'perulangan/looping barisEnd WithMsgBox ("Tambahan Berhasil Diimport"), vbInformation, "INFO"End If
Command2.Caption = "LOAD" 'mengembalikan button menjadi LOADMSFlexGrid1.Clear 'membersihkan data yang ada di grid
Tidak ada komentar:
Posting Komentar