OleDB selecting multiple CSVs with first row as fi

2019-07-10 15:57发布

So my code looks like this currently, which is all fine and good

String q = "SELECT * FROM "+"test.csv";
        try
        {
            OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\;Extended Properties=\"Text;HDR=No;FMT=Delimited\"");
            OleDbDataAdapter da = new OleDbDataAdapter();
            DataSet ds = new DataSet();
            OleDbCommand cd = new OleDbCommand(q, cn);
            cn.Open();
            da.SelectCommand = cd;
            ds.Clear();
            da.Fill(ds, "CSV");
            dataGridView1.DataSource = ds.Tables[0];
            cn.Close();
            }
        catch (Exception ex)
        {
            MessageBox.Show("There was an issue: " + ex.Message);
        }

However, I would like to take the first row in my CSV and use that as the field names, so I can do something like

"select a.ID, a.SOMETHING_ELSE from test.csv a"
where the CSV looks something like
ID,SOMETHING_ELSE,DONT_WANT_THIS
1,blah,I don't want to see this

Yet, from what I see, about all examples on the web show nothing other than select *, and I would like my datagrid to show the headers as the field names selected, instead of F1, F2....

Is this implemented anywhere?

标签: c# csv oledb
1条回答
贪生不怕死
2楼-- · 2019-07-10 16:57

Change your connection string to include HDR=Yes (instead of HDR=No):

OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\;Extended Properties=\"Text;HDR=Yes;FMT=Delimited\"");

For OleDB, the HDR property in the connection string indicates whether or not the first row contains the column names.

查看更多
登录 后发表回答