2016-07-11 17 views
0

テキスト/ datファイルのデータをC#のデータテーブルにロードするには、ここで私は動的にする必要がありますテキストファイルのデータに基づいて列を生成します。これは何ですかテキストファイル/データファイルからデータを読み込む方法c#

+0

[データテーブルにテキストファイルを読み取る方法]の可能な重複(http://stackoverflow.com/questions/20860101/how-to-read-text-file-to-datatable) – Draken

答えて

0
 private static System.Data.DataTable SplitColumns() 
     {  
      System.Data.DataTable table = new System.Data.DataTable("dataFromFile"); 
      string file="textfile.txt" ==>Get file which you want to split into columns 

      using (StreamReader sr = new StreamReader(file)) 
      { 
       string line; 
       int rowsCount = 0; 
       while ((line = sr.ReadLine()) != null) 
       { 

        string[] data = line.Split(new string[] { "\t"," " }, StringSplitOptions.RemoveEmptyEntries);==>here i'm using the tab delimeter to split the row line 
                               ==>in the file to columns data,You can use your own delimeter 


        if(table.Columns.Count==0) 
        { 
        for (int i = 1; i <= data.Length; i++) 
        { 

         table.Columns.AddRange(new DataColumn[] { new DataColumn("col"+(i).ToString(), typeof(string)) });==>here i'm dynamically creating the column headers 
                                  ==> based on the strings in the line 
        } 
        } 
        table.Rows.Add(); 
        for (int i = 0; i < data.Length; i++) 
        { 
         if (data[i].Contains(" ")) 
          data[i] = data[i].Replace(" ", ""); 
         if (!data[i].Equals("")) 
          table.Rows[rowsCount][i] = data[i]; 
        } 
        rowsCount++; 
       } 
      } 
      return table; 
     } 
+1

?あなたのコードは動作していませんか?もしそうなら、それを質問と共に掲示する必要があります。 – user3185569

+0

入力テキストファイルの外観は? –

+0

"次のテキストをテキストファイルに追加し、上記のコードを適用する" h1 h2 h3 1 2 3 –

関連する問題