-4

以下はそのコードです。

protected void Upload(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                //Upload and save the file
                string csvPath = Server.MapPath("~/App_Data/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
                FileUpload1.SaveAs(csvPath);


            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[7] 
            {
            new DataColumn("pataintno", typeof(int)),
            new DataColumn("Firstname", typeof(string)),
            new DataColumn("Lastname",typeof(string)),
            new DataColumn("Age", typeof(int)),
            new DataColumn("Address", typeof(string)),
            new DataColumn("Email", typeof(string)),
            new DataColumn("Phno", typeof(int)),});


            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 consString = ConfigurationManager.ConnectionStrings["cnstr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(consString))
            {
                using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
                {
                    //Set the database table name
                    sqlBulkCopy.DestinationTableName = "Pataint";
                    con.Open();
                    sqlBulkCopy.WriteToServer(dt);
                    con.Close();
                    Array.ForEach(Directory.GetFiles((Server.MapPath("~/App_Data/"))), File.Delete);
                }
            }
        }
        else
        {
            Label1.Text = "PlZ TRY AGAIN";
        }
    }
4

3 に答える 3

1

整数型の 3 つのフィールドを持つ DataTable があります。エラーは、ファイルから抽出された 1 つ以上のデータが有効な整数ではないことを示しています。

したがって、不正な入力をチェックする必要があります(これらの場合はいつものように)

    // Read all lines and get back an array of the lines
    string[] lines = File.ReadAllLines(csvPath);

    // Loop over the lines and try to add them to the table
    foreach (string row in lines)
    {
        // Discard if the line is just null, empty or all whitespaces
        if (!string.IsNullOrWhiteSpace(row))
        {
            string[] rowParts = row.Split(',');

            // We expect the line to be splittes in 7 parts. 
            // If this is not the case then log the error and continue
            if(rowParts.Length != 7)
            {
                // Log here the info on the incorrect line with some logging tool
                continue;
            }

            // Check if the 3 values expected to be integers are really integers
            int pataintno;
            int age;
            int phno;

            if(!Int32.TryParse(rowParts[0], out pataintno))
            {
               // It is not an integer, so log the error
               // on this line and continue
               continue;
            }
            if(!Int32.TryParse(rowParts[3], out age))
            {
               // It is not an integer, so log the error
               // on this line and continue
               continue;
            }
            if(!Int32.TryParse(rowParts[6], out phno))
            {
               // It is not an integer, so log the error
               // on this line and continue
               continue;
            }

            // OK, all is good now, try to create a new row, fill it and add to the 
            // Rows collection of the DataTable
            DataRow dr = dt.NewRow();
            dr[0] = pataintno;
            dr[1] = rowParts[1].ToString();
            dr[2] = rowParts[2].ToString();
            dr[3] = age
            dr[4] = rowParts[4].ToString();
            dr[5] = rowParts[5].ToString();
            dr[6] = phno;
            dt.Rows.Add(dr);
        }
    }

入力のチェックは、文字列を整数に変換できない場合に false を返すInt32.TryParseを使用して行われます。この場合、何らかのエラー ログを作成して、ループが完了したときに確認し、どの行が正しくないかを見つけて修正する必要があります。

いくつかの点でコードを変更したことにも注意してください: File.ReadAllLines を使用して、新しい行ごとに入力が分割されているようにします (改行が単なる a\nまたは\r\nコードの場合は問題ありません)。新しい行を追加するコードもデータテーブルはパターンに従う必要があります。新しい行を作成し、値を入力し、新しい行を既存のコレクションに追加します。

于 2014-12-25T10:09:41.493 に答える
0

コードを確認しましたが、問題ないようです。csv ファイルをチェックして、どの列にもヘッダーがないことを確認することをお勧めします。

于 2015-01-03T14:39:01.490 に答える
0

今日、csvをsqlテーブルに解析しているときにこの問題が発生しました。私のパーサーは 1 年間正常に動作していましたが、今日突然 int 変換エラーがスローされました。SQL一括コピーはそれほど有益ではなく、csvファイルを確認してもデータに問題はありません。csv のすべての数値列に有効な数値がありました。

エラーを見つけるために、カスタムメソッドの下に書きました。最初のレコードですぐにエラーが発生しました。実際の問題は、ベンダーが数値の csv 形式を変更し、整数の代わりに小数値のレンダリングを開始したことです。たとえば、値 1 の代わりに、csv ファイルには 1.0 がありました。csvファイルを開くと1しか反映されませんが、メモ帳では1.0と表示されました。私のSQLテーブルにはすべて整数値があり、どういうわけかSQL BulkCopyはこの変換を処理できません. このエラーを把握するのに約 3 時間かかりました。
から着想を得たソリューション - https://sqlbulkcopy-tutorial.net/type-a-cannot-be-converted-to-type-b

  private void TestData(CsvDataReader dataReader)
    {
        int a = 0;
        while(dataReader.Read())
        {
            try
            {
                a = int.Parse(dataReader[<<Column name>>].ToString());
            }
            catch (Exception ex){}
        }
    } 
于 2020-12-28T20:19:24.013 に答える