Whenever I import data from an Excel file that is inside the IIS Express folder, everything goes fine without errors, and the Excel file goes to the table that I create in SQL, but when the Excel file is in another place, it gives that error... Why?
Here's my code:
protected void Upload_Click(object sender, EventArgs e)
{
string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(excelPath);
string filepath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filepath);
string ext = Path.GetExtension(filename);
String strConnection = @"Data Source=PEDRO-PC\SQLEXPRESS;Initial Catalog=costumizado;Persist Security Info=True;User ID=sa;Password=1234";
string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=\"Excel 12.0 Xml;HRD=YES;IMEX=1;\"";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
OleDbCommand cmd = new OleDbCommand("Select [Nome],[Cidade],[Idade] from [Folha1$]", excelConnection);
excelConnection.Open();
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("Select [Nome],[Cidade],[Idade] from [Folha1$]", strConnection);
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "Teste";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
The error is on line:
excelConnection.Open();
User contributions licensed under CC BY-SA 3.0