Saturday, 10 June 2017

How to export DataTable to CSV file in C#

In this article, I am going to explain how to export DataTable values to Comma Separated Value (CSV) excel file using C#.Net. A CSV file contains data with columns separated by comma. If you open a CSV file using Excel, then column and row data will be automatically filled in excel cells.

Below images shows how the CSV file look like when you open CSV file in text editor and in Excel.

CSV File GeneratedOpen in NotepadOpen in Excel
C# CSV file generated How to create CSV file in C# Export datatable in CSV file using C#

Related Articles

How to insert bulk of records from a text file in SQL-Server

Creating DataTable

First of all create a dummy DataTable in C# by using the code given below.

DataTable dt = new DataTable();
dt.Columns.Add("EmpId", typeof(Int32));
dt.Columns.Add("EmpName", typeof(string));
dt.Columns.Add("EmpCountry", typeof(string));
dt.Rows.Add(1, "Rahul", "India");
dt.Rows.Add(2, "John", "USA");
dt.Rows.Add(3, "Mary", "UK");
dt.Rows.Add(4, "Mathew", "Australia");

Export C# DataTable to CSV File

Below is the C# code to convert DataTable to CSV file in C#.

IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
                                  Select(column => column.ColumnName);

StringBuilder sb = new StringBuilder();

sb.AppendLine(string.Join(",", columnNames));

foreach (DataRow row in dt.Rows)
    string[] fields = row.ItemArray.Select(field => field.ToString()).
    sb.AppendLine(string.Join(",", fields));

File.WriteAllText("E:\\Employee.csv", sb.ToString());


Post a Comment

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive