Importing Excel into SQL using ASP.NET 2.0 and SqlBulkCopy
We were recently faced with a challenge at work where the client wanted to provide an Excel file of data which could be imported into SQL and used to update data within certain tables. While this is a snap via Enterprise Manager, it's trickier when the client wants it all to happen on the back-end so they can do it themselves via a web form.
While there are numerous tutorials for exporting data into Excel format, there didn't seem to be many on how to get the data in, so I'm posting this function in the hopes that it helps someone else.
I've stripped out most of the code so that this is JUST the part that imports the data from Excel. This example assumes that the.xls file is already on your server in the same location as this script. You can write your own upload functions to get it there. (If you need help with uploading, let me know and I'll post an article on that as well) This also assumes that you have a table in SQL that matches the schema of your spreadsheet.
This uses the new SqlBulkCopy class in ASP.NET 2.0 which lets you easily copy bulk amounts of data from one source to another.
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System.Web.Configuration
...
'Declare Variables - Edit these based on your particular situation
Dim sSQLTable As String = "TempTableForExcelImport"
Dim sExcelFileName As String = "myExcelFile.xls"
Dim sWorkbook As String = "[WorkbookName$]"
'Create our connection strings
Dim sExcelConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath(sExcelFileName) & ";Extended Properties=""Excel 8.0;HDR=YES;"""
Dim sSqlConnectionString As String = WebConfigurationManager.ConnectionStrings("MyConnectionString").ToString
'Execute a query to erase any previous data from our destination table
Dim sClearSQL = "DELETE FROM " & sSQLTable
Dim SqlConn As SqlConnection = New SqlConnection(sSqlConnectionString)
Dim SqlCmd As SqlCommand = New SqlCommand(sClearSQL, SqlConn)
SqlConn.Open()
SqlCmd.ExecuteNonQuery()
SqlConn.Close()
'Series of commands to bulk copy data from the excel file into our SQL table
Dim OleDbConn As OleDbConnection = New OleDbConnection(sExcelConnectionString)
Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM " & sWorkbook), OleDbConn)
OleDbConn.Open()
Dim dr As OleDbDataReader = OleDbCmd.ExecuteReader()
Dim bulkCopy As SqlBulkCopy = New SqlBulkCopy(sSqlConnectionString)
bulkCopy.DestinationTableName = sSQLTable
bulkCopy.WriteToServer(dr)
OleDbConn.Close()
NOTE: I left out any error handling functionality for the sake of brevity but it would be a good idea to use a Try/Catch block to handle any exceptions