2017-06-21 8 views
0

次のコードは、sqlserver2016テーブルからデータを読み取り、それをローカルフォルダにダンプします。一部の列の値にはコンマが含まれています。これはカンマを使用していた区切り文字として別​​の列に値を置き換えます。したがって、カンマを値に保持できますが、別の列に値を置き換えないでください。私のコードサンプルは以下の通りです。どんな助けもありがとう。cのカラム値からエスケープ文字#

SqlConnection myADONETConnection = new SqlConnection(); 
myADONETConnection = (SqlConnection)(Dts.Connections["db_connection"].AcquireConnection(Dts.Transaction) as SqlConnection); 



      //Read data from table or view to data table 
      string query = SQLQuery; 
      SqlCommand cmd = new SqlCommand(query, myADONETConnection); 
      //myADONETConnection.Open(); 
      DataTable d_table = new DataTable(); 
      d_table.Load(cmd.ExecuteReader()); 
      myADONETConnection.Close(); 



      string FileFullPath = DestinationFolder + "\\" + FileNamePart + "_" + datetime + FileExtension; 

      StreamWriter sw = null; 
      sw = new StreamWriter(FileFullPath, false); 

      // Write the Header Row to File 
      int ColumnCount = d_table.Columns.Count; 
      for (int ic = 0; ic < ColumnCount; ic++) 
      { 
       sw.Write(d_table.Columns[ic]); 
       if (ic < ColumnCount - 1) 
       { 
        sw.Write(FileDelimiter); 
       } 
      } 
      sw.Write(sw.NewLine); 

      // Write All Rows to the File 
      foreach (DataRow dr in d_table.Rows) 
      { 
       for (int ir = 0; ir < ColumnCount; ir++) 
       { 
        if (!Convert.IsDBNull(dr[ir])) 
        { 
         sw.Write(dr[ir].ToString()); 
        } 
        if (ir < ColumnCount - 1) 
        { 
         sw.Write(FileDelimiter); 
        } 
       } 
       sw.Write(sw.NewLine); 

      } 

      sw.Close(); 

      Dts.TaskResult = (int)ScriptResults.Success; 
+1

あなたが変位して何を意味引用符は?あなたが得る出力、あなたが取得したいものを与えることができますか? – Doruk

+0

データベースの値の例、列名:データと値: "これはサンプル"です。しかし、私はcsvファイルの値に2つの別の列に "この"と "サンプル"として、私は全体の値 "これは、サンプルは" CSVの1つの列にする必要があります秋に書く場合 – Sumon

+1

ダブルを使用することはできません価値がある場合はそれを引用します。 –

答えて

2

すべての値を引用符で囲みます。これはカンマをエスケープし、後でファイルを解析するために使用するものであれば理解する必要があります。

「CSVにエスケープのデフォルトの方法です。

次は、トリックを行う必要があります。これは、あなたのデータは任意の引用符が含まれていないと仮定しない。

sw.Write('"'); 
sw.Write(dr[ir].ToString()); 
sw.Write('"'); 

あなたのデータが含まれていない場合あなたがそれらをエスケープするために、以下に示すように、それらを倍増する必要があります。

value1 | value2 | super"special"value 
"value1","value2","super""special""value" 
+0

大変ありがとうございます。問題を解決してくれてありがとうございます – Sumon

+0

引用符やその他の文字が含まれている場合はどうすれば対応できますか – Sumon

関連する問題