问题
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();
}
回答1:
I would recommend using the EPPlus open source free library which you can install through Nuget or visit(https://www.nuget.org/packages/EPPlus/) which reads Excel files without having Excel or any other Interops installed.
Below is the updated code using Epplus. I am assuming you don't have a header row in your excel file(if you do just change the var row = 1 to var row = 2 which would mean to start at Row 2 and ignore the header)
using (var con = new SqlConnection(@"Data Source=NT;Initial Catalog=StudentDB;Integrated Security=True"))
{
con.Open();
var excelFile = new FileInfo(@"TestFile.xlsx");
using (var epPackage = new ExcelPackage(excelFile))
{
var worksheet = epPackage.Workbook.Worksheets.First();
for (var row = 1; row <= worksheet.Dimension.End.Row; row++)
{
var rowValues = worksheet.Cells[row, 1, row, worksheet.Dimension.End.Column];
var cmd = new SqlCommand("INSERT INTO Persons(ContactID, FirstName, SecondName, Age) VALUES (@contactid, @firstname, @secondname, @age)", con);
cmd.Parameters.AddWithValue("@contactid", rowValues["A1"].Value);
cmd.Parameters.AddWithValue("@firstname", rowValues["B1"].Value);
cmd.Parameters.AddWithValue("@secondname", rowValues["C1"].Value);
cmd.Parameters.AddWithValue("@age", rowValues["D1"].Value);
cmd.ExecuteNonQuery();
}
}
}
Some of the parameters in your AddWithValue didn't match the parameter you declared in your insert statement, and I cleaned those up as well. Using the code I was able to read a test xlsx file I created to match your layout and insert into the database. Hope it helps.
来源:https://stackoverflow.com/questions/46720971/how-to-upload-an-excel-file-data-into-sql-server-without-oledb