Creating a simple UI allows you to export data from DataTable to CSV file as shown below.

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)
{
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);
}
Adding click event handler to the Export button allows you to export datatable to csv file.
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);
}
}
}
}
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.