Export Datatable to CSV Using Extension Method

Introduction

I would like to share how to export a DataTable to Comma Separated File (CSV) format using an Extension method.

In this document we will also learn how to use Extension methods to make code more manageable.

About 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

Procedure

a. Create DataTable

We added a class containing a method returning a DataTable

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.
 
dt.ToCSV() will call the ToCSV method defined in the CSVutlity class.



f. Running the code

The following will be the output:



Open this file in notepad.

file in notepad

By default this file opens into Excel.

Double-click to open this file in Excel.



Refrences
Basic of Extension method
http://www.c-sharpcorner.com/UploadFile/deveshomar/extension-method-in-C-Sharp/

Conclusion

We have learned how to use an Extension method and learned how to export a DataTable to a CSV file.

Up Next
    Ebook Download
    View all
    Learn
    View all