我一直在尝试使用ASP.NET Core MVC将数据从Excel文件导入到SQL Server中。但是,这只是代码不运行:如何在没有oledb的情况下将Excel文件数据上载到SQL Server中
[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();
}
这段代码有什么问题?任何错误?你调试了代码并检查它里面发生了什么? –
它说(“TestFile.xlsx”),不能从字符串更改为System.IO.Stream – ohhhkeo
你能帮我编码如何上传Excel文件数据并存储到我的visual studio 2017的sqlserver吗? 我不知道从哪里开始 – ohhhkeo