Export DataTable To CSV In C#

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 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 a 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 created dynamically. In your case, your DataTable may be created via DataSet that fetches 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 an Extension Method that converts the DataTable to CSV 

  • Create a static class as per the code below:
    1. public static class  CSVUtlity  { }
  • Add an Extension method as in the following:
    1. public static void ToCSV(this DataTable dtDataTable, string strFilePath)
    2.            
  • 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.     StreamWriter sw = new StreamWriter(strFilePath, false);  
    3.     //headers    
    4.     for (int i = 0; i < dtDataTable.Columns.Count; i++) {  
    5.         sw.Write(dtDataTable.Columns[i]);  
    6.         if (i < dtDataTable.Columns.Count - 1) {  
    7.             sw.Write(",");  
    8.         }  
    9.     }  
    10.     sw.Write(sw.NewLine);  
    11.     foreach(DataRow dr in dtDataTable.Rows) {  
    12.         for (int i = 0; i < dtDataTable.Columns.Count; i++) {  
    13.             if (!Convert.IsDBNull(dr[i])) {  
    14.                 string value = dr[i].ToString();  
    15.                 if (value.Contains(',')) {  
    16.                     value = String.Format("\"{0}\"", value);  
    17.                     sw.Write(value);  
    18.                 } else {  
    19.                     sw.Write(dr[i].ToString());  
    20.                 }  
    21.             }  
    22.             if (i < dtDataTable.Columns.Count - 1) {  
    23.                 sw.Write(",");  
    24.             }  
    25.         }  
    26.         sw.Write(sw.NewLine);  
    27.     }  
    28.     sw.Close();  

    d. Export to CSV on button click

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

    e. Call ToCSV method

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

    f. Build and run the 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 the 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. 
     

    References and more

     
    Learn here about extension methods, Extension Methods in C#

    Similar Articles