I have the following code in the controller to import data from an Excel file:
public ActionResult importarExcel()
{
var retorno = 0;
for (int i = 0; i < Request.Files.Count; i++)
{
var fileuploader = Request.Files[i];
if (fileuploader.ContentLength > 0)
{
string Foldername;
string Extension = System.IO.Path.GetExtension(fileuploader.FileName);
string filename = Path.GetFileName(fileuploader.FileName.ToString());
if (Extension == ".XLS" || Extension == ".XLSX" || Extension == ".xls" || Extension == ".xlsx")
{
Foldername = Server.MapPath("~/Importados/");
fileuploader.SaveAs(Foldername + filename.ToString());
String conStr = "";
switch (Extension)
{
case ".xls": //Excel 97-03
conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Foldername + "//" + filename + ";" +
"Extended Properties=Excel 8.0;";
break;
case ".xlsx": //Excel 07
conStr = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + Foldername + "//" + filename + ";" +
"Extended Properties=Excel 8.0;";
break;
}
OleDbConnection oconn = new OleDbConnection();
oconn.ConnectionString = conStr;
OleDbCommand ocmd = new OleDbCommand("select * from [Sheet1$]", oconn);
oconn.Open();
OleDbDataReader odr = ocmd.ExecuteReader();
string partida = "";
string Description1 = "";
string Quantity1 = "";
string OriginalPrice1 = "";
string Image1 = "";
string Shape; string Carat; string Certificate;
while (odr.Read())
{
partida = valid(odr, 0);
Description1 = valid(odr, 1);
Quantity1 = valid(odr, 2);
OriginalPrice1 = valid(odr, 3);
Image1 = valid(odr, 4);
Shape = valid(odr, 5);
Carat = valid(odr, 6);
Certificate = valid(odr, 7);
// you will get row by value
}
}
}
}
return Json(retorno);
}
protected string valid(OleDbDataReader myreader, int stval)//if any columns are found null then they are replaced by zero
{
object val = myreader[stval];
if (val != DBNull.Value)
return val.ToString();
else
return Convert.ToString(0);
}
But it turns out that when I try to open the connection on the line oconn.Open () after the OleDbCommand, I get the following error:
The provider 'Microsoft.ACE.OLEDB.12.0' is not registered on the local machine.
The file I try to import in an excel file of office 2016.
If anyone knows anything, your help is appreciated. Thank you in advance.