Im currently building a project that lets users import Excel files via a web interface (built), which saves the file to the server (built), and then imports the data into the SQL Database on the server depending on a few of the user options (not built).

Im not familiar with SQL database tools within VS at all so I have been fumbling around for the better part of two days just trying to get everything set up. Im pretty sure I need to use BulkCopy, but Im not quite sure how to use it and I can't seem to find specific examples that explain it pertaining to my specific application.

So in my App_Data folder I have an .mdf title "Device Database." In that database I have three tables: "Galaxy Nexus", "Hercules" , and "Ruby"

I am trying to import four cells from each imported excel sheet to their respective tables.

I would like to import cell(2,2) to column1 in the table, cell(2,3) to column2, cell(3,2) to column3 and cell(1,1) to column4.

The code I am trying to accomplish this with is:

    Dim ExcelContentType As String = "application/vnd.ms-excel"
    Dim Excel2010ContentType As String = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    Dim excelConnectionString As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", SavedFile)
    Using connection As New OleDbConnection(excelConnectionString)
        Dim Command As OleDbCommand = New OleDbCommand("Select * FROM [Sheet1$]", connection)
        connection.Open()
        Using reader As DbDataReader = Command.ExecuteReader()
            Dim sqlConnectionString As String = "Data Source=.\sqlexpress;Initial Catalog=ExcelDB;Integrated Security=True"
            Using bulkCopy As New SqlBulkCopy(sqlConnectionString)
                bulkCopy.DestinationTableName = DropDown1.SelectedItem.ToString
                bulkCopy.WriteToServer(reader)
            End Using
        End Using
    End Using

Where I am having trouble is, I do not know how to select certain cells from the excel sheet to import and I do not know how to copy those cells to specific columns in the specified table.

Any and all help is always appreciated. Thanks, Zach

share|improve this question
I use the Excel COM libraries. Then you can just write insert and/or update queries (or use stored procedures). msdn.microsoft.com/en-us/library/wss56bz7%28v=vs.100%29.aspx – Marnee Sep 11 '12 at 22:29
I use the COM libraries too when I am automating excel scripts or transferring excel to excel. Can you work with SQL Databases like excel? Can I go NexusGaxaxyTable.column1(or whatever) = XLSheet1.Cells(2,2).Value.ToString, once both are open? – Nefarii Sep 11 '12 at 22:40
I don't think so. I usually just craft an insert or update query. You would have to work with t-sql. For example, get the value in the cell and use that to update the table: msdn.microsoft.com/en-us/library/ms177523.aspx – Marnee Sep 11 '12 at 22:56
I can post sample code in c# if you like. – Marnee Sep 11 '12 at 22:59
That would be really helpful. Could you post a few comments on it too so I can translate it to VB.net? – Nefarii Sep 13 '12 at 22:31

2 Answers

Use Excel Data Reader dll for this. It will read the excel file and give the Dataset as result.

share|improve this answer
ExcelDataReader will give a set of DataTables inside Dataset. There are nothing but each work sheet. Definitely good stuff !! – Murali Sep 12 '12 at 9:17
Im kinda confused about this. I see that it can read the data from an Excel sheet and export it into a data set fairly easily, but how do you put that dataset into a SQL table? More specifically, how would you take a few cells out of excel and put them into specific columns in the SQL table? – Nefarii Sep 13 '12 at 22:34
That you have to write a code for filtering the columns from DataSet and then code for Database update. The component will give only DataSet. – Murali Sep 14 '12 at 5:34
Im sure I can figure out the dataset part, would you happen to know the code to add values to a particular column in a specific table? I'm struggling to find a way to open a database and add information to it. – Nefarii Sep 14 '12 at 16:00
up vote 1 down vote accepted

Im posting an answer so that if anyone else stumbles upon this, they might be helped as well.

This is what got everything to work for me. (Shout out to kevin)

Protected Sub Button1_Click(sender As Object, e As System.EventArgs)
    Dim appPath As String = Request.PhysicalApplicationPath
        Dim con As New System.Data.SqlClient.SqlConnection
        con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=" & appPath & "App_Data\Devicedatabase.MDF;Integrated Security=True;User Instance=True;"
        con.Open()
        MsgBox("open")
        con.Close()
        MsgBox("close")
    End Sub

This got the connection open after much trying and frustration.

This got the excel values imported to the database:

 Using con As New SqlClient.SqlConnection With
{
    .ConnectionString =
    "Data Source=.\SQLEXPRESS;AttachDbFilename=" & appPath & "App_Data\Devicedatabase.MDF;Integrated Security=True;User Instance=True;"
}
Using cmd As New SqlClient.SqlCommand With
    {
        .Connection = con,
        .CommandText = "INSERT INTO " & """" & DropDownList1.SelectedItem.ToString & """" & "ColumnName1, ColumnName2)VALUES (@Col1,@Col2)"
    }
    cmd.Parameters.Add(New SqlClient.SqlParameter With {.DbType = DbType.String, .ParameterName = "@Col1"})
    cmd.Parameters.Add(New SqlClient.SqlParameter With {.DbType = DbType.String, .ParameterName = "@Col2"})
    cmd.Parameters(0).Value = "Value obtained from Excel"
    cmd.Parameters(1).Value = "Value obtained from Excel"
    con.Open()
    Dim Result As Integer = cmd.ExecuteNonQuery
    If Result <> 1 Then
        MessageBox.Show("Insert failed.")
    Else
        MessageBox.Show("Row inserted.")
    End If

End Using
End Using

Enjoy guys!

share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.