如何从CSV文件中选择前4列并运行查询

本文关键字:4列 运行 查询 选择 CSV 文件 | 更新日期: 2023-09-27 18:27:00

我有一个方法,我想查询CSV文件中的第三列,但我只想显示前四列。我希望做一些类似的事情

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的标题行。

感谢

如何从CSV文件中选择前4列并运行查询

将select语句更改为:

query = "select F3 from " + file;

以检索第三列。如果您想添加标题,则将连接字符串更改为包括HDR=YES,并以与普通查询相同的方式按名称引用列:

query = "select mycolumn from " + file;