How to upload an Excel file data into SQL Server without oledb

佐手、 提交于 2020-01-30 02:51:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!