Reputation: 1
I have been digging from last 4 hours to find a simplest solution to import a csv file into datagridview in C# and i am unable to find the appropriate solution.
then hopelessly, I decided to ask user to convert csv to excel first and then import but its too unromantic. here is the code for importing excel:
string pathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtPath.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
OleDbConnection conn = new OleDbConnection(pathConn);
OleDbDataAdapter ODA = new OleDbDataAdapter("Select *from [" + txtSheet.Text + "$]", conn);
DataTable dt = new DataTable();
ODA.Fill(dt);
dataGridView1.DataSource = dt;
Question: To import CSV, what should be the connectionString using this code.? Or there is no simple soultion?
Upvotes: 0
Views: 4347
Reputation: 3625
I have this snippet from my old project, hope this helps:
string csvFile = System.IO.Path.Combine(Application.StartupPath, "aCSVfile.csv");
List<string[]> rows = File.ReadAllLines(csvFile).Select(x => x.Split(',')).ToList();
DataTable dataTable = new DataTable();
//add cols to datatable:
dataTable.Columns.Add("col0");
dataTable.Columns.Add("col1");
rows.ForEach(x => { dataTable.Rows.Add(x); });
dataGridView.DataSource = dataTable;
Upvotes: 1