Background: I have a asp.net web pages (razor) application on a 2008R2 web server that has a page with an excel upload button which allows the user to post excel data to a SQL Server 2014 table. In order to get it to work on the dev server I had to install the Microsoft Access Database Engine 2010 as outlined in this MikesDotNetting blog post. However, I have been encouraged to find a way to import data to the production server that doesn't require installing Microsoft Access Database Engine on the server. I have a C# Windows Forms app that does the same thing but I am not good at converting Windows Forms app code to my razor web sites.
I actually didn't expect this code below to work since I am posting data to SQL Server 2014 and according to MS OleDB has been deprecated and has not been supported since SQL Server 2012.
Q1 - Does deprecated just mean 'use at your own risk' or does it mean it shouldn't work on 2014 at all?
The code below (which occurs right after my if...ISPOST) works great for getting an excel file uploaded to my web server then inserted into a SQL Server 2014 table. I just need to find a way to make it work without installing Microsoft Access Database Engine to the production server 2008 R2 IIS7.
Q2 - Is there some Nuget Package or other workaround that might help?
Q3 - Is there a quick fix to convert that OLE DB connection string to ODBC?
Q4 - Is there a namespace / assembly I could add to the project that would not require the access database engine install on the server?
Code:
try
{
// import code
var excel = Request.Files[0];
var file = Path.Combine(Server.MapPath("~/Upload_Folder/"), excel.FileName);
excel.SaveAs(file);
var excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=Yes;IMEX=1\"";
var sqlConnectionString = ConfigurationManager.ConnectionStrings["MYCONNECTIONSTRING"].ToString();
var excelData = new DataTable();
using (var myConnection = new OleDbConnection(string.Format(excelConnectionString, file)))
{
var myCommand = new OleDbCommand("SELECT * FROM [Sheet1$]", myConnection);
var myAdapter = new OleDbDataAdapter(myCommand);
myAdapter.Fill(excelData);
using (var destinationConnection = new SqlConnection(sqlConnectionString))
{
destinationConnection.Open();
using (var bulkCopy = new SqlBulkCopy(destinationConnection))
{
bulkCopy.DestinationTableName = "MYTABLE";
bulkCopy.ColumnMappings.Add("CODE", "code");
bulkCopy.ColumnMappings.Add("TITLE", "title");
bulkCopy.ColumnMappings.Add("LAST_NAME", "last_name");
bulkCopy.ColumnMappings.Add("FIRST_NAME", "first_name");
}
}
if (Directory.Exists(Path.GetDirectoryName(file)))
{
File.Delete(file);
}
}
}
catch (Exception ex)
{
throw ex;
}