Dim excelPath As String = Server.MapPath("~/") + Path.GetFileName(FileUpload1.PostedFile.FileName)
FileUpload1.SaveAs(excelPath)
Dim connString As String = String.Empty
Dim extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
Select Case extension
Case ".xls"
'Excel 97-03
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & excelPath & ";Extended Properties='Excel 8.0'"
Exit Select
Case ".xlsx"
'Excel 07 or higher
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & excelPath & ";Extended Properties='Excel 12.0 Xml;HDR=Yes'"
Exit Select
End Select
Using excel_con As New OleDbConnection(connString)
excel_con.Open()
Dim sheet1 As String = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing).Rows(0)("TABLE_NAME").ToString()
Dim dtExcelData As New DataTable()
Using oda As New OleDbDataAdapter("SELECT * FROM [" & sheet1 & "]", excel_con)
oda.Fill(dtExcelData)
End Using
excel_con.Close()
Dim count As Int16
count = dtExcelData.Columns.Count
Dim conString As String = ConfigurationManager.ConnectionStrings("ConnectionString1").ConnectionString
Using con As New SqlConnection(conString)
Using sqlBulkCopy As New SqlBulkCopy(con)
'Set the database table name
sqlBulkCopy.BulkCopyTimeout = 0
sqlBulkCopy.DestinationTableName = "dbo.employee"
'[OPTIONAL]: Map the Excel columns with that of the database table
'Below mapping required when your column name with excel is not matched
'sqlBulkCopy.ColumnMappings.Add("employee_id", "employee_id")
'sqlBulkCopy.ColumnMappings.Add("name", "name")
con.Open()
sqlBulkCopy.WriteToServer(dtExcelData)
con.Close()
End Using
End Using
End Using