banner



How To Create A Csv File In C#

  • Updated date Nov 02, 2020
  • 537.7k
  • 12

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 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.             table.Columns.Add("ID" , typeof ( int ));
  7.             table.Columns.Add("NAME" , typeof ( string ));
  8.             table.Columns.Add("CITY" , typeof ( string ));
  9.             table.Rows.Add(111,"Devesh" , "Ghaziabad" );
  10.             table.Rows.Add(222,"ROLI" , "KANPUR" );
  11.             table.Rows.Add(102,"ROLI" , "MAINPURI" );
  12.             table.Rows.Add(212,"DEVESH" , "KANPUR" );
  13.             table.Rows.Add(102,"NIKHIL" , "GZB" );
  14.             table.Rows.Add(212,"HIMANSHU" , "NOIDa" );
  15.             table.Rows.Add(102,"AVINASH" , "NOIDa" );
  16.             table.Rows.Add(212,"BHUPPI" , "GZB" );
  17. return  table;
  18.           }
  19.     }

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. for  ( int  i = 0; i < dtDataTable.Columns.Count; i++) {
    4.         sw.Write(dtDataTable.Columns[i]);
    5. if  (i < dtDataTable.Columns.Count - 1) {
    6.             sw.Write("," );
    7.         }
    8.     }
    9.     sw.Write(sw.NewLine);
    10. foreach (DataRow dr in  dtDataTable.Rows) {
    11. for  ( int  i = 0; i < dtDataTable.Columns.Count; i++) {
    12. if  (!Convert.IsDBNull(dr[i])) {
    13. string  value = dr[i].ToString();
    14. if  (value.Contains( ',' )) {
    15.                     value = String.Format("\"{0}\"" , value);
    16.                     sw.Write(value);
    17.                 }else  {
    18.                     sw.Write(dr[i].ToString());
    19.                 }
    20.             }
    21. if  (i < dtDataTable.Columns.Count - 1) {
    22.                 sw.Write("," );
    23.             }
    24.         }
    25.         sw.Write(sw.NewLine);
    26.     }
    27.     sw.Close();
    28. }

    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);
    5. }

    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.

    How To Create A Csv File In C#

    Source: https://www.c-sharpcorner.com/UploadFile/deveshomar/export-datatable-to-csv-using-extension-method/

    Posted by: lujanthicents.blogspot.com

    0 Response to "How To Create A Csv File In C#"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel