How to read .csv file in C#
By FoxLearn 7/16/2024 8:56:14 AM 29.54K
CSV (Comma Separated Values) is a simple text format, in which values are separated by commas. CSV format is frequently used to save small-scale spreadsheets such as contacts, lists, reports, etc.
A CSV file contains many lines including values separated by commas. The first line of the CSV text contains the names of each column in the spreadsheet, each separated by a comma (except the first and last column). All subsequent rows have the same structure, containing the corresponding values of each column.
Both CSV and Excel (.xls, .xlsx) are files that help save data as spreadsheets. Both can be opened with spreadsheet software (spreadsheet software) such as Microsoft Excel, Google Sheests, Polaris Office, Libre Office, etc.). The functions and formulas supported by spreadsheet software will be applicable to both types of files when opened with that software.
How to read .csv file in C#
To play demo, you should create a new Windows Forms Application by clicking New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "ReadCsvFile" and then click OK button.
Drag and drop DataGridView and Button controls from the Visual toolbox to your form designer, then design your form as shown below.
Reading a CSV file in C# using OleDb can be done by treating the CSV file as if it were a database, with OleDb provider for CSV.
Here's how you can do it.
C# csv to datatable oledb
Creating a ReadCsv method that allows you to read data from csv file into DataTable in c#.
//oledb csv parser public DataTable ReadCsv(string fileName) { DataTable dt = new DataTable("Data"); // you need to create a connection string for OleDb using (OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" + Path.GetDirectoryName(fileName) + "\";Extended Properties='text;HDR=yes;FMT=Delimited(,)';")) { // you need to create a query to select data from the CSV file, then execute select query using (OleDbCommand cmd = new OleDbCommand(string.Format("select *from [{0}]", new FileInfo(fileName).Name), cn)) { cn.Open(); using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd)) { adapter.Fill(dt); } } } return dt; }
This method treats each line of the CSV file as a row in a database table and each comma-separated value as a column in that row. The HDR=Yes
in the connection string tells OleDb that the first row of the CSV file contains column headers.
If your file doesn't have headers, set HDR=No.
You can easily parse your csv file to DataTable using OleDb in c#.
oledb csv connection string
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" + Path.GetDirectoryName(fileName) + "\";Extended Properties='text;HDR=yes;FMT=Delimited(,)';"
Adding a click event handler to the Open button allows you to load data from csv file to DataGridView.
//Read CSV file and fill into DataTable C# private void btnOpen_Click(object sender, EventArgs e) { try { //Open file dialog, allows you to select a csv file using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "CSV|*.csv", ValidateNames = true, Multiselect = false }) { if (ofd.ShowDialog() == DialogResult.OK) dataGridView.DataSource = ReadCsv(ofd.FileName); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
Remember to handle exceptions appropriately and ensure that the necessary OleDb provider is installed on your system. Through this c# example, I hope so you've learned how to read csv file in c# windows application. From there, you can apply to your real projects.
VIDEO TUTORIAL