Mohanapriya R Mohanapriya R
Updated date Jul 23, 2024
In this article, we will learn how to convert DataTables to CSV files in C#.

How to Convert DataTable to CSV in C#?

Let's see how we can convert a DataTable to a CSV file using C#.

using System;
using System.Data;
using System.IO;

class Program
{
    static void Main()
    {
        // Sample DataTable
        DataTable dataTable = new DataTable();
        dataTable.Columns.Add("ID", typeof(int));
        dataTable.Columns.Add("Name", typeof(string));
        dataTable.Rows.Add(1, "Raj");
        dataTable.Rows.Add(2, "Peter");

        // Convert DataTable to CSV
        string csvData = DataTableToCSV(dataTable);

        // Write CSV data to a file
        File.WriteAllText("output.csv", csvData);
        
        Console.WriteLine("CSV file created successfully.");
    }

    static string DataTableToCSV(DataTable dataTable)
    {
        StringWriter writer = new StringWriter();
        foreach (DataRow row in dataTable.Rows)
        {
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                if (i != 0)
                    writer.Write(",");
                writer.Write(row[i].ToString());
            }
            writer.WriteLine();
        }
        return writer.ToString();
    }
}

Output:

After running the program, a file named "output.csv" will be created in the same directory as the executable. Opening this file will see the following content:

ID,Name
1,Raj
2,Peter

Comments (0)

There are no comments. Be the first to comment!!!