【发布时间】:2017-10-13 00:54:04
【问题描述】:
我一直在尝试使用 ASP.NET Core MVC 将数据从 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
-
您能帮我编写有关如何上传 excel 文件数据并存储到我的 Visual Studio 2017 的 sqlserver 中的代码吗?我不知道从哪里开始
-
如果您不想使用 oledb,您可以探索办公互操作库。您可以使用它读取excel文件。
-
Excel XLS(X) 是一个二进制文件,你不能轻易地将它解析为 CSV 格式的文本(改用字节数组)。您可以尝试使用 EPPlus、NPOI 或 Office interop 等其他库来获取 Excel 文件内容。
标签: c# asp.net-mvc excel asp.net-core asp.net-core-mvc