I have been trying to import data from an Excel file into SQL Server with ASP.NET Core MVC. But this code just doesn't run:
[HttpPost]
public IActionResult Index(ICollection<IFormFile> files)
{
string line;
using (SqlConnection con = new SqlConnection(@"Data Source=NT;Initial Catalog=StudentDB;Integrated Security=True"))
{
con.Open();
using (StreamReader file = new StreamReader("TestFile.xlsx"))
{
while ((line = file.ReadLine()) != null)
{
string[] fields = line.Split(',');
SqlCommand cmd = new SqlCommand("INSERT INTO Persons(ContactID, FirstName, SecondName, Age) VALUES (@contactid, @firstname, @secondname, @age)", con);
cmd.Parameters.AddWithValue("@id", fields[0].ToString());
cmd.Parameters.AddWithValue("@firstname", fields[1].ToString());
cmd.Parameters.AddWithValue("@secondname", fields[2].ToString());
cmd.ExecuteNonQuery();
}
}
}
return View();
}