2012-02-03 19 views
1

私はCSVを解析し、そこからDataTableを構築しようとしています。ここで難しいのは、データテーブルを作成する前にデータ型を割り当てることです。例えばのために は以下のCSVは私が構築していたデータテーブルに文字列として保存されている名前、小数などのIntや給与など年齢を持っていると思いタイプCSVファイルの解析

Name,Age,Salary 
A,30,1000 
B,35,1500 
C,40,2000 

ファイル考えます。これを行う最善の方法に関する提案はありますか?ここで

+1

をCSVファイルにしてくださいプログラムは '30'と' 1000'を区別し、前者を 'int'とし、後者を' decimal'と見なします。他の情報が提供されるまでこれを行うことはできません。たとえば、列名とデータ型との間のマッピングである。 oledbを使用できる場合は –

+1

。 schema.iniを使用して列タイプを定義することができます。これをチェックしてくださいhttp://stackoverflow.com/questions/8683180/data-error-when-reading-csv-file-in-c-sharp-winforms/8683365#8683365 –

+0

ありがとうShoaib。それは私が望んでいた方法で動作します。 Schema.iniが答えでした。 – Nishant

答えて

1

は、ほとんどのエラーチェック、およびいくつかの良いコーディング慣行を無視素朴な実装です:

namespace StackOverflowConsole 
{ 
    using System; 
    using System.IO; 
    using System.Data; 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      var path = @"C:\temp\test.csv"; 

      CreateTestFile(path); 

      var dataTable = new DataTable(); 
      dataTable.Columns.Add("Name", typeof(string)); 
      dataTable.Columns.Add("Age", typeof(int)); 
      dataTable.Columns.Add("Salary", typeof(decimal)); 

      // TODO: add checks, exception handling 
      using (var reader = new StreamReader(path)) 
      { 
       // reads all lines into a single string 
       var lines = reader.ReadToEnd().Split(new char[] { '\n' }); 

       if (lines.Length > 0) 
       { 
        // you may wanna skip the first line, if you're using a file header 
        foreach (string line in lines) 
        { 
         if (string.IsNullOrWhiteSpace(line)) 
         { 
          continue; 
         } 

         // split the current line using the separator 
         var tokens = line.Trim().Split(new char[] { ',' }); 

         // check your assumptions on the CSV contents 
         // ex: only process lines with the correct number of fields 
         if (tokens.Length == 3) 
         { 
          var person = new Person(); 

          person.Name = tokens[0]; 
          // a better implementation would use TryParse() 
          person.Age = Int32.Parse(tokens[1]); 
          person.Salary = Decimal.Parse(tokens[2]); 

          dataTable.Rows.Add(person.Name, person.Age, person.Salary); 
         } 
        } 
       } 
      } 
     } 

     private static void CreateTestFile(string path) 
     { 
      if (File.Exists(path)) 
      { 
       File.Delete(path); 
      } 

      using (var writer = new StreamWriter(path)) 
      { 
       writer.WriteLine("A,30,1000"); 
       writer.WriteLine("B,35,1500"); 
       writer.WriteLine("C,40,2000"); 
      } 
     } 
    } 

    public class Person 
    { 
     public string Name; 
     public int Age; 
     public decimal Salary; 
    } 
} 
0

はこれを試してみてください:

どのようにできたコードディレクトリに

string path = Server.MapPath("emp.csv"); 
      string header = "Yes"; 
      string sql = string.Empty; 
      DataTable dt = null; 
      string fullpath = Path.GetDirectoryName(path); 
      string fileName = Path.GetFileName(path); 
      OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fullpath + ";Extended Properties=\"Text;HDR=" + header + "\""); 
      OleDbDataAdapter da = new OleDbDataAdapter("select * from [" + fileName + "]", connection); 
      dt = new DataTable(); 
      dt.Columns.Add("Name", typeof(string)); 
      dt.Columns.Add("Age", typeof(int)); 
      dt.Columns.Add("Salary", typeof(decimal)); 
      da.Fill(dt); 
      GridView1.DataSource = dt; 
      GridView1.DataBind(); 
関連する問題