Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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#.


IEnumerablestring> columnNames = dt.Columns.Cast().
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()).
ToArray();
sb.AppendLine(string.Join(",", fields));
}

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


This post first appeared on ASPArticles, please read the originial post: here

Share the post

How to export DataTable to CSV file in C#

×

Subscribe to Asparticles

Get updates delivered right to your inbox!

Thank you for your subscription

×