2012-03-06 51 views
0

我有一个方法,我想查询CSV文件中的第3列,但我只想显示前四列。我希望能做类似我如何从我的CSV文件中选择前4列并运行查询

SELECT * FROM Table WHERE User-Name='%PERSON%' 

但将它应用于我的CSV文件。

public static DataTable ParseCSV(string path, String pattern) 
    { 
     if (!File.Exists(path)) 
      return null; 
     string full = Path.GetFullPath(path); 
     string file = Path.GetFileName(full); 
     string dir = Path.GetDirectoryName(full); 
     string connString = "Provider=Microsoft.Jet.OLEDB.4.0;" 
      + "Data Source=\"" + dir + "\\\";" 
      + "Extended Properties=\"text;HDR=No;FMT=Delimited\""; 
     string query = "SELECT F1, F2, F3 FROM " + file; 
     DataTable dTable = new DataTable(); 
     OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString); 
     try 
     { 
      dAdapter.Fill(dTable); 
     } 
     catch (InvalidOperationException ioe) 
     { 
      Console.WriteLine(ioe.Message.ToString()); 
     } 
     dAdapter.Dispose(); 
     return dTable; 
    } 


    private void buttonSearch_Click(object sender, EventArgs e) 
    { 
     path = textBoxFilePath.Text.ToString().Trim(); 
     //BindingSource to sync DataTable and DataGridView 
     BindingSource bSource = new BindingSource(); 
     //set the BindingSource DataSource 
     bSource.DataSource = ParseCSV(path, pattern); 
     dataGridView1.DataSource = bSource; 
    } 

另外我的CSV文件有一个标题行,我想成为我的DataGridView标题行。

感谢

回答

1

改变你的SELECT语句:

query = "select F3 from " + file; 

检索第三列。如果您要添加的头,然后更改连接字符串包括HDR = YES和你会为一个正常的查询以同样的方式按名称引用列:

query = "select mycolumn from " + file; 
+0

你怎么WHERE子句工作或获取标题行(out或datagridview标题) – 2012-03-06 15:22:20

+0

我相信HDR参数告诉喷气引擎将第一行视为列名称。 – linkerro 2012-03-06 15:24:10

+0

谢谢,我明白了! – 2012-03-06 15:34:58

相关问题