Windows Forms: How to Export DataTable to CSV using CsvHelper in C#

This post shows you How to Export DataTable to CSV using CsvHelper in C# Windows Forms Application.

Drag and drop DataGridView, Button controls from your Visual Studio toolbox into your form designer, then design a simple windows forms allows you to export datatable to csv file using CsvHelper in c# as shown below.

c# write csv

Right-clicking on your project, then select Manage Nuget Packages from the Visual Studio.

Next, Search 'CsvHelper', then download and install it.

c# csvhelper

CsvHelper is an open source library helps you read and write csv files. It's extremely fast, flexible, and easy to use. Supports reading and writing of custom class objects.

Adding a bindingsource to the DataGridView allows you to binding customer data from the Northwind database.

private void frmExportDataTableToCsvUsingCsvHelper_Load(object sender, EventArgs e)
{
    // TODO: This line of code loads data into the 'appData.Customers' table. You can move, or remove it, as needed.
    this.customersTableAdapter.Fill(this.appData.Customers);
}

How to export datatable to csv in c#

Adding a click event handler to the Export button allows you to export datatable to csv file using CsvHelper in c#.

// export datatable to csv c#
private void btnExportData_Click(object sender, EventArgs e)
{
    using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "CSV files|*.csv" })
    {
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            try
            {
                // create csv in c#
                using (var textWriter = File.CreateText(sfd.FileName))
                {
                    using (CsvWriter csv = new CsvWriter(textWriter, System.Globalization.CultureInfo.CurrentCulture))
                    {
                        DataTable dt = this.appData.Customers.CopyToDataTable();
                        // write datatable to csv c#
                        foreach (DataColumn column in dt.Columns)
                            csv.WriteField(column.ColumnName);
                        csv.NextRecord();
                        // convert datatable to csv c#
                        foreach (DataRow row in dt.Rows)
                        {
                            for (var i = 0; i < dt.Columns.Count; i++)
                                csv.WriteField(row[i]);
                            csv.NextRecord();//csvhelper datatable to csv
                        }
                    }
                }
                MessageBox.Show("You have successfully exported the file.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

Using CreateText of File class to create your file, then use the CsvWriter class to write data from your DataTable to csv file using WriteField method, the NextRecord method allows you to append new line.

Here's a simple example of how to write datatable to csv c#, using CsvHelper third party library is a simple way to export data from DataTable to CSV file