Technical Article

Create INSERT statements from Excel

,

Problem:
I am working on a project where I need to populate some configuration settings from an Excel file to the SQL server database so that on considering the values only my package will run. Here I want some easy method to populate those Excel data to my SQL server database. So that there will be no need to write Insert statements daily for each record. I want this task to be automated.

Solution:
Excel files includes a very good functionality called Macro execution. And the good thing is that we can write our own macro in VB and then we can execute it inside the Excel file. Here I too did the same thing, written one macro that will create INSERT statements for the current activated sheet.
To write Macro in Excel 2007:

  • Navigate to View tab in Excel

  • In View ribbon click on Macros Button

  • In the Macro Dialog box, give a valid name for a macro you want to create, and press Create button

  • In the code window, enter the script given below:

 

The code is self descriptive; in this I am fetching all the columns for the given active sheet at first. Then it will fetch the values for the corresponding columns. It will ask you for the range of data to be fetched like the starting Row no and the maximum Row no.
Testing:
Let's take the example of a small table named Student and the data for this is:

NameRollMarks
Ram10189
Ashok10293
Kumar10378

In excel sheet it will look like this:

Here the starting row no is 2 and maximum row no is 4.
So after giving the inputs to the script, it will generate the below code:

insert into [Student] ( [Name] , [Roll] , [Marks] )
values( 'Ram', '101', '89');

insert into [Student] ( [Name] , [Roll] , [Marks] )
values( 'Ashok', '102', '93');

insert into [Student] ( [Name] , [Roll] , [Marks] )
values( 'Kumar', '103', '78');

Conclusion:
Creating a macro to generate Insert statements from the excel file is very handy and easy than importing data from excel to SQL server or by package creation. The code can be further customized to generate insert statements for all the sheets given in an excel file.

Sub CreateInsertScript()
 Dim Row As Integer
 Dim Col As Integer

 'To store all the columns available in the current active sheet
 Dim ColNames(100) As String

 Col = 1
 Row = 1
 Dim ColCount As Integer
 ColCount = 0
 'Get Columns from the sheet
 Do Until ActiveSheet.Cells(Row, Col) = "" 'Loop until you find a blank.
 ColNames(ColCount) = "[" + ActiveSheet.Cells(Row, Col) + "]"
 ColCount = ColCount + 1
 Col = Col + 1
 Loop
 ColCount = ColCount - 1

 'Inputs for the starting and ending point for the rows
 Row = InputBox("Give the starting Row No.")
 Dim MaxRow As Integer
 MaxRow = InputBox("Give the Maximum Row No.")

 'File to save the generated insert statements
 File = "c:\\InsertCode.txt"
 fHandle = FreeFile()
 Open File For Output As fHandle

 Dim CellColCount As Integer
 Dim StringStore As String 'Temporary variable to store partial statement

 Do While Row <= MaxRow
 StringStore = ""
 CellColCount = 0
 'ActiveSheet.Name will give the current active sheet name
 'this can be treated as table name in the database
 StringStore = StringStore + "insert into [" + ActiveSheet.Name + "] ( "
 Do While CellColCount <= ColCount
 StringStore = StringStore + ColNames(CellColCount)
 'To avoid "," after last column
 If CellColCount <> ColCount Then
 StringStore = StringStore + " , "
 End If
 CellColCount = CellColCount + 1
 Loop
 'Here it will print "insert into [TableName] ( [Col1] , [Col2] , ..."
 Print #fHandle, StringStore + " ) "

 'For printing the values for the above columns
 StringStore = " values( "
 CellColCount = 0
 Do While CellColCount <= ColCount
 StringStore = StringStore + " '" + CStr(ActiveSheet.Cells(Row, CellColCount + 1)) + "'"
 If CellColCount <> ColCount Then
 StringStore = StringStore + ", "
 End If
 CellColCount = CellColCount + 1
 Loop

 'Here it will print "values( 'value1', 'value2', ..."
 Print #fHandle, StringStore + ");"
 Print #fHandle, " "
 Row = Row + 1


 Loop


 Close #fHandle
 MsgBox ("Successfully Done")
 End Sub

Rate

4.63 (16)

You rated this post out of 5. Change rating

Share

Share

Rate

4.63 (16)

You rated this post out of 5. Change rating