2014-03-18 47 views
0

我從Excel工作表導入數據在學生記錄以.xls,因爲它是當我打電話的功能上傳Excel中是得到錯誤無效的轉換,從「System.String」到「的System.Guid」

文件擴展名
public ActionResult Importexcel() 
     { 


      if (Request.Files["FileUpload1"].ContentLength > 0) 
      { 
       string extension = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName); 
       string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), 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)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-UserInfo-20140318063343.mdf;Initial Catalog=aspnet-UserInfo-20140318063343;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"; 
       //Create Connection to Excel work book 
       OleDbConnection excelConnection = new OleDbConnection(excelConnectionString); 

       //Create OleDbCommand to fetch data from Excel 
       OleDbCommand cmd = new OleDbCommand("Select [Id],[Name],[StudentId] from [Sheet1$]", excelConnection); 

       excelConnection.Open(); 
       OleDbDataReader dReader; 
       dReader = cmd.ExecuteReader(); 

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

       // SQL Server Connection String 


      } 

      return RedirectToAction("Import"); 
     } 

我收到以下錯誤,從 'System.String' 到 '的System.Guid'

無效轉換。

我的模型是下面,我不能改變的Guid,因爲它是我的必然要求

public class StudentRecord 
    { 

     public long Id { get; set; } 
     public string Name { get; set; } 

     public Guid StudentId { get; set; } 

    } 
+0

不知道到工作表的OLE訪問是否都會有這個,但新的OleDbCommand(「選擇[ID],[名],演員(StudentId作爲唯一標識符)作爲StudentID ..」可能會做工作 –

回答

1
studentRecord.Guid = new Guid("Mystring"); 

也許,你必須itarate槽從數據庫中得到了什麼SOU的對象,並解析上由一個達到上面的陳述。

你也可以看看使用TypeConverter。

0

將字符串解析爲系統Guid,如下所示。它可以幫助你

System.Guid.Parse(yourStringVariable); 
相關問題