我正在尝试使用C#在asp.net中将.csv文件数据导入(上传)到我的数据库中,但收到通知,提示输入的字符串格式不正确。请帮忙。谢谢!
错误行:dt.Rows [dt.Rows.Count-1] [i] =单元格;
// 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文件数据和数据表的顺序是否相同。在BirthYear,Number,PostalCode,TrainingPlaces之类的列中,如果不同格式的数据将引发此错误,则为int数据类型。上载前请检查。使用try catch块显示消息。
当我尝试在System.Data.dll中发生类型为'System.ArgumentException'的异常但未在用户代码中处理时,会出现此类错误消息
Additional information: Input string was not in a correct format.Couldn't store <Family Name> in BirthYear Column. Expected type is Int32.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句