Export DataTable To CSV In C#

Learn how to export a DataTable to a Comma Separated File (CSV) file using a C# extension method.

Introduction


In this article and code sample, I would like to share how to export a DataTable to a Comma Separated File (CSV) format using an a C# extension method. We will also learn how to use an extension method to make code more manageable.
 

What is a .csv file


A  Comma Separated Value (CSV) file contains data with all the columns in the file separated by a comma. Another use of a CSV file is to directly open the file in Excel and then the data will be auto-filled into Excel cells.

The following is snapshot of a sample CSV file:

 CSV file
 
Here is the process of creating a DataTable and exporting its data to a .csv file.
 

a. Create a DataTable


We added a class containing a method that returns a DataTable. The DataTable is ceated dynamically. In your case, your DataTable may be created via DataSet that fetch data from a database. If you're new to ADO.NET and DataTable, first read this: DataTable in C#

Code:
  1. public static class OperationsUtlity  
  2.      {  
  3.         public static DataTable createDataTable()  
  4.         {  
  5.             DataTable table = new DataTable();     
  6.                 //columns  
  7.             table.Columns.Add("ID"typeof(int));     
  8.             table.Columns.Add("NAME"typeof(string));     
  9.             table.Columns.Add("CITY"typeof(string));    
  10.   
  11.                 //data  
  12.             table.Rows.Add(111, "Devesh""Ghaziabad");     
  13.             table.Rows.Add(222, "ROLI""KANPUR");     
  14.             table.Rows.Add(102, "ROLI""MAINPURI");     
  15.             table.Rows.Add(212, "DEVESH""KANPUR");  
  16.             table.Rows.Add(102, "NIKHIL""GZB");  
  17.             table.Rows.Add(212, "HIMANSHU""NOIDa");  
  18.             table.Rows.Add(102, "AVINASH""NOIDa");  
  19.             table.Rows.Add(212, "BHUPPI""GZB");  
  20.               
  21.              return table;  
  22.           }  
  23.          
  24.     } 

Code snapshot:



b. Create UI to display DataTable


Here we created a simple DataGridView to bind to the DataTable.

Create UI to display Datatable

Code



c. Create Extension Method that converts the DataTable to CSV 

  • Create a static class as per the code below:
    1. public static class  CSVUtlity  
    2.  { } 
  • Add an Extension method as in the following:
    1. public static void ToCSV(this DataTable dtDataTable, string strFilePath)  
    2.         {    
    3.          } 
    This method takes the DataTable as its parameter, that's why it is an extension method.

  • After adding the Extension method the ToCSV method is now appearing in the list below:


  • The following is the code to convert the DataTable to CSV:
    1. public static void ToCSV(this DataTable dtDataTable, string strFilePath)  
    2.         {     
    3.             StreamWriter sw = new StreamWriter(strFilePath, false);  
    4.             //headers  
    5.             for (int i = 0; i < dtDataTable.Columns.Count; i++)  
    6.             {  
    7.                 sw.Write(dtDataTable.Columns[i]);  
    8.                 if (i < dtDataTable.Columns.Count - 1)  
    9.                 {  
    10.                     sw.Write(",");  
    11.                 }  
    12.             }  
    13.             sw.Write(sw.NewLine);  
    14.             foreach (DataRow dr in dtDataTable.Rows)  
    15.             {  
    16.                 for (int i = 0; i < dtDataTable.Columns.Count; i++)  
    17.                 {  
    18.                     if (!Convert.IsDBNull(dr[i]))  
    19.                     {  
    20.                         string value = dr[i].ToString();  
    21.                         if (value.Contains(','))  
    22.                         {  
    23.                             value = String.Format("\"{0}\"", value);  
    24.                             sw.Write(value);  
    25.                         }  
    26.                         else  
    27.                         {  
    28.                             sw.Write(dr[i].ToString());  
    29.                         }  
    30.                     }  
    31.                     if (i < dtDataTable.Columns.Count - 1)  
    32.                     {  
    33.                         sw.Write(",");  
    34.                     }  
    35.                 }  
    36.                 sw.Write(sw.NewLine);  
    37.             }  
    38.             sw.Close();  
    39.         }  

d. Export to CSV on button click

  1. private void btnCSV_Click(object sender, EventArgs e)  
  2.         {  
  3.             DataTable dt = OperationsUtlity.createDataTable();  
  4.             string filename = OpenSavefileDialog();  
  5.             dt.ToCSV(filename);  
  6.   
  7.               
  8.         }  

 

e. Call ToCSV method

 
dt.ToCSV() will call the ToCSV method defined in the CSVutlity class.



f. Build and run project


Now build and run the project. Click on the button to export data. The output file will be test.csv.



When you open the csv file in Notepad, you will see this:

file in notepad

By default this file opens in Excel. Double-click to open this file in Excel. This is how file looks like.

 

Conclusion


We have learned how to use a C# extension method and learned how to export a DataTable to a CSV file. 
 

Refrences and more


Learn here about extension methods, Extension Methods in C#