2015-03-25 108 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.