How to Export DataTable to CSV in C#

By FoxLearn 7/16/2024 9:36:47 AM   4.68K
Exporting a DataTable to a CSV file in a C# Windows Forms application involves iterating through the rows and columns of the DataTable and writing them to a CSV file.

How to Export DataTable to CSV in C#

Here's a step-by-step guide on how to do this:

Create a Windows Forms Application in Visual Studio. then design a simple UI allows you to export data from DataTable to CSV file as shown below.

c# export datatable to csv

Creating a WriteDataTable method allows you to write data from DataTable to text or csv file in c#.

public void WriteDataTable(DataTable dataTable, TextWriter writer, bool header)
{
    if (header)
    {
        // Create the CSV file and write the headers
        IEnumerable<string> headerValues = dataTable.Columns
            .OfType<DataColumn>()
            .Select(column => QuoteValue(column.ColumnName));
        writer.WriteLine(string.Join(",", headerValues));
    }
    IEnumerable<string> items = null;
    foreach (DataRow row in dataTable.Rows)
    {
        items = row.ItemArray.Select(o => QuoteValue(o?.ToString() ?? string.Empty));
        writer.WriteLine(string.Join(",", items));
    }
    writer.Flush();
}

private string QuoteValue(string value)
{
    return string.Concat("\"", value.Replace("\"", "\"\""), "\"");
}

Data in the csv file is separated by commas. If you want to export header data you need to write column headers first, then data.

Next, Add a bindingsource to the DataGridView allows you to retrieve customer table from the Northwind database.

private void frmExportDataTableToCsv_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);
}

Double-click on the Export button to generate an event handler for its click event allows you to export datatable to csv file.

// c# export datatable to csv
private void btnExportData_Click(object sender, EventArgs e)
{
    using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "CSV files|*.csv" })
    {
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            try
            {
                using (StreamWriter writer = new StreamWriter(sfd.FileName))
                {
                    WriteDataTable(this.appData.Customers.CopyToDataTable(), writer, true);
                }
                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);
            }
        }
    }
}

Build and run your application. When you click the button, it will export the data from the DataTable to a CSV file. You can easily open csv file with Microsoft Excel.

Through this c# example, you can easily export data from DataGridView to csv file in c# windows forms application.