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();
}
}
錯誤信息本身就已說明不處理!在你的CSV文件中,你可能有你想要在DataTable的int列中分配的字符串值。 – 2015-03-25 06:55:17
有一個斷點並且看到,由於將字符串值添加到其數據類型爲int的列,您會遇到此問題。 – thevan 2015-03-25 07:04:36