Export C# DataTable to CSV file

This code will help you to write C# datatable to a csv file with headers. You can also define your own desired csv delimiter (comma, semicolon, pipe etc.)

Below given code snippet demonstrates the example of exporting data stored in C# datatable to a csv file.

Step 1: Use this namespace at the starting of your code.

using System.IO;

Step 2: Declare the variable to hold the path of CSV file on which CSV file will be exported and delimiter of CSV file.

string CsvFilePath = @"D:\TEST\Sample_CSV.csv";
char csvDelimiter = ';';

Step 3: Define the function as below

public void SaveToCSV(DataTable DT,char csvDelimiter)
{
  try
  {
   // code block for writing headers of data table

   int columnCount = DT.Columns.Count;
   string columnNames = "";
   string[] output = new string[DT.Rows.Count + 1];
   for (int i = 0; i < columnCount; i++)
    {
      columnNames += DT.Columns[i].ToString() + csvDelimiter;
    }
   output[0] += columnNames;

   // code block for writing rows of data table
   for (int i = 1; (i - 1) < DT.Rows.Count; i++)
   {
    for (int j = 0; j < columnCount; j++)
     {
      output[i] += DT.Rows[i - 1][j].ToString() + csvDelimiter;
     }
   }

 System.IO.File.WriteAllLines(filename, output, System.Text.Encoding.UTF8);
  }
}

If you do not want to write headers in csv file, you do not need to add code block for writing headers.

Leave a Reply