DEV Community

Cover image for Export DataTable To CSV In C#
LetsUpdateSkills
LetsUpdateSkills

Posted on

3

Export DataTable To CSV In C#

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.

Image description

Here is the process of creating a DataTable and exporting its data to a .csv file.

Step 1. 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.

public static class OperationsUtility
{
    public static DataTable CreateDataTable()
    {
        DataTable table = new DataTable();

        // Define columns
        table.Columns.Add("ID", typeof(int));
        table.Columns.Add("NAME", typeof(string));
        table.Columns.Add("CITY", typeof(string));

        // Add data rows
        table.Rows.Add(111, "Devesh", "Ghaziabad");
        table.Rows.Add(222, "ROLI", "KANPUR");
        table.Rows.Add(102, "ROLI", "MAINPURI");
        table.Rows.Add(212, "DEVESH", "KANPUR");
        table.Rows.Add(102, "NIKHIL", "GZB");
        table.Rows.Add(212, "HIMANSHU", "NOIDa");
        table.Rows.Add(102, "AVINASH", "NOIDa");
        table.Rows.Add(212, "BHUPPI", "GZB");

        return table;
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2. Create UI to display DataTable

Here we created a simple DataGridView to bind to the DataTable.

Image description

I took Window Form.

Image description

Step 3. Create an Extension Method that converts the DataTable to CSV

public static void ToCSV(this DataTable dtDataTable, string strFilePath) {
    StreamWriter sw = new StreamWriter(strFilePath, false);
    //headers
    for (int i = 0; i < dtDataTable.Columns.Count; i++) {
        sw.Write(dtDataTable.Columns[i]);
        if (i < dtDataTable.Columns.Count - 1) {
            sw.Write(",");
        }
    }
    sw.Write(sw.NewLine);
    foreach(DataRow dr in dtDataTable.Rows) {
        for (int i = 0; i < dtDataTable.Columns.Count; i++) {
            if (!Convert.IsDBNull(dr[i])) {
                string value = dr[i].ToString();
                if (value.Contains(',')) {
                    value = String.Format("\"{0}\"", value);
                    sw.Write(value);
                } else {
                    sw.Write(dr[i].ToString());
                }
            }
            if (i < dtDataTable.Columns.Count - 1) {
                sw.Write(",");
            }
        }
        sw.Write(sw.NewLine);
    }
    sw.Close();
}
Enter fullscreen mode Exit fullscreen mode

Step 4. Export to CSV on button click

Please click here to see complete article

API Trace View

Struggling with slow API calls?

Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay