2015-11-05 78 views
0

我是MVC ASP.NET的新手,嘗試從Excel文件導入數據並將數據加載到數據庫中。將數據從Excel文件移動到數據庫

數據庫已創建,其列名與Excel文件中的信息匹配。當我上載的Excel文件,然後點擊提交,我得到的錯誤:

format of the initialization string does not conform to specification

基礎上調試故障出在下面一行,目前甚至不知道代碼的其餘部分是正確的:

excelConnection.Open(); 

查找類似的錯誤問題,但答案不起作用。對於這部分的完整代碼:

//Code at Controller and cshtml 
public ActionResult Import() 
    { 
     return View(); 
    } 

    public ActionResult ImportExcel() 
    { 
     try 
     { 
      if (Request.Files["FileUpload1"].ContentLength > 0) 
      { 
       string extension = Path.GetExtension(Request.Files["FileUpload1"].FileName); 
       string path1 = string.Format("{0}/{1}", Server.MapPath("~/App_Data/uploads"), Request.Files["FileUpload1"].FileName); 
       if (System.IO.File.Exists(path1)) 
        System.IO.File.Delete(path1); 

       Request.Files["FileUpload1"].SaveAs(path1); 

       string sqlConnectionString = @"Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\ExampleDB.mdf;Initial Catalog=aspnet-FormulaOne-20151105055609;Integrated Security=True"; 

       //Create connection string to Excel work book 
       string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=Excel 12.0;Persist Security Info=False, HDR=YES"; 
       //Create Connection to Excel work book 
       OleDbConnection excelConnection = new OleDbConnection(excelConnectionString); 
       //Create OleDbCommand to fetch data from Excel 
       OleDbCommand cmd = new OleDbCommand("Select [Speed],[Average],[Power],[Comment] from [Sheet1$]", excelConnection); 

       //ERROR OCCURING AT THIS LINE 
       excelConnection.Open(); 
       OleDbDataReader dReader; 
       dReader = cmd.ExecuteReader(); 

       SqlBulkCopy sqlBulk = new SqlBulkCopy(sqlConnectionString); 
       //Give your Destination table name 
       sqlBulk.DestinationTableName = "Stats"; 
       sqlBulk.WriteToServer(dReader); 
       excelConnection.Close(); 

       // SQL Server Connection String 
      } 

      return RedirectToAction("Import"); 
     } 

     catch (Exception e) 
     { 
      Console.WriteLine(e.StackTrace.ToString()); 
      return RedirectToAction("Import"); 
     } 
    } 
} 

@using (Html.BeginForm("Importexcel", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    <table> 
     <tr><td>Excel file</td><td><input type="file" id="FileUpload1" name="FileUpload1" /></td></tr> 
     <tr><td></td><td><input type="submit" id="Submit" name="Submit" value="Submit" /></td></tr> 
    </table> 
} 
+0

嘗試。拋出一個新錯誤 - 「SaveAs方法被配置爲需要一個根路徑,並且路徑'@c:\ users \ name \ documents \ visual studio 2015 \ Projects \ Example \ App_Data \ uploads/Book1.xlsx'沒有根「。 – cubeb

回答

0

我認爲你的問題是程序不能夠找到正確的Excel文件,我建議使用OleDbConnection

  //path to your file 
      string path = @"D:\your\path\to\excel\file.xlsx"; 
      // noitice that parameter HRD=YES if your file has header 
      string connStr = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES""", path); 


      using (OleDbConnection connection = new OleDbConnection(connStr)) 
       { 
        connection.Open(); 
        // ensure that sheet name is correct 
        OleDbCommand command = new OleDbCommand("select * from [sheet$]", connection); 
        using (OleDbDataReader dr = command.ExecuteReader()) 
         { 
          // here you can access rows and insert them respectively 
          //first column , first row 
          var name = dr[0].toString(); 
          //second column , first row 
          var lastname = dr[1].toString(); 
          //here you can do anything with this variables (ex insert to db) 
         } 

       } 
相關問題