2017-10-13 67 views
0

我一直在尝试使用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(); 
} 
+0

这段代码有什么问题?任何错误?你调试了代码并检查它里面发生了什么? –

+0

它说(“TestFile.xlsx”),不能从字符串更改为System.IO.Stream – ohhhkeo

+0

你能帮我编码如何上传Excel文件数据并存储到我的visual studio 2017的sqlserver吗? 我不知道从哪里开始 – ohhhkeo

回答

0

我会建议使用EPPlus开源免费的,你可以通过的NuGet或访问(https://www.nuget.org/packages/EPPlus/)安装读取Excel文件,而无需Excel或任何其他互操作性展示安装的库。

以下是使用Epplus更新的代码。我假设你没有标题行中的Excel文件(如果你只是改变了var行= 1到VAR行= 2这将意味着第2行开始,而忽略了头)

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(); 
       } 

      } 

     } 

AddWithValue中的一些参数与您在insert语句中声明的参数不匹配,我也清理了这些参数。使用代码我能够读取我创建的测试xlsx文件,以匹配您的布局并插入到数据库中。希望能帮助到你。

+0

感谢您的帮助,我尝试使用您提供的代码。我试图运行它,它来到一个空白页。>< – ohhhkeo

+0

调试时出现什么错误?你在数据库中看到记录吗? – Darthchai

+0

没有错误。应用程序可以运行,但它只是进入空白页面。 没有记录被添加到数据库中。 – ohhhkeo

相关问题