OleDB selecting multiple CSVs with first row as field names in C#
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 (Exce开发者_运维问答ption 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?
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.
精彩评论