2015-03-25 104 views
0

我試圖使用C#在asp.net中將一個.csv文件數據導入(上載)到我的數據庫中,但得到通知,有一個輸入字符串isn沒有正確的格式。請幫忙。謝謝!「輸入字符串格式不正確」用於文件上傳

錯誤行:dt.Rows [dt.Rows.Count - 1] [i] = cell;

// Upload and save file 
    string csvPath = Server.MapPath("~/FileUploads/") + Path.GetFileName(FileUpload1.PostedFile.FileName); 
    FileUpload1.SaveAs(csvPath); 

    DataTable dt = new DataTable(); 
    dt.Columns.AddRange(new DataColumn[11] { new DataColumn("Name", typeof(string)), 
     new DataColumn("NRIC", typeof(string)), 
     new DataColumn("Gender", typeof(string)), 
     new DataColumn("BirthYear", typeof(int)), 
     new DataColumn("Number", typeof(int)), 
     new DataColumn("PostalCode", typeof(int)), 
     new DataColumn("CoursesAttended", typeof(string)), 
     new DataColumn("Language", typeof(string)), 
     new DataColumn("DateAttended", typeof(string)), 
     new DataColumn("TrainingPlaces", typeof(int)), 
     new DataColumn("Remarks", typeof(string)) }); 

    string csvData = File.ReadAllText(csvPath); 

    foreach (string row in csvData.Split('\n')) 
    { 
     if (!string.IsNullOrEmpty(row)) 
     { 
      dt.Rows.Add(); 
      int i = 0; 

      foreach (string cell in row.Split(',')) 
      { 
       dt.Rows[dt.Rows.Count - 1][i] = cell; 
       i++; 
      } 
     } 
    } 

    string conString = ConfigurationManager.ConnectionStrings["SilverInfocomm"].ConnectionString; 

    using (SqlConnection con = new SqlConnection(conString)) 
    { 
     using (SqlBulkCopy bulk = new SqlBulkCopy(con)) 
     { 
      // Set database table name 
      bulk.DestinationTableName = "dbo.FileUploads"; 
      con.Open(); 
      bulk.WriteToServer(dt); 
      con.Close(); 
     } 
    } 
+0

錯誤信息本身就已說明不處理!在你的CSV文件中,你可能有你想要在DataTable的int列中分配的字符串值。 – 2015-03-25 06:55:17

+0

有一個斷點並且看到,由於將字符串值添加到其數據類型爲int的列,您會遇到此問題。 – thevan 2015-03-25 07:04:36

回答

-2

檢查.csv文件,數據和數據表都在同一順序與否。 在像BirthYear,Number,PostalCode,TrainingPlaces這樣的列中,如果不同的格式數據會引發此錯誤,那麼TrainingPlaces就是int數據類型。上傳前請檢查 。 使用try catch塊顯示消息。

這種類型的錯誤消息加薪,當我試圖 類型「System.ArgumentException」的異常出現在System.Data.dll中,但在用戶代碼中

Additional information: Input string was not in a correct format.Couldn't store <Family Name> in BirthYear Column. Expected type is Int32.