How to Export DataTable to CSV in C#
By FoxLearn 2/17/2025 2:09:43 AM 5.33K
How to Export DataTable to CSV in C#?
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.
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.
C# DataSet to CSV
To export a DataSet
to a CSV file in C#, you can loop through the tables and rows of the DataSet
, and write the data to a CSV file.
using System; using System.Data; using System.IO; using System.Text; class Program { static void Main() { // Sample DataSet for demonstration DataSet dataSet = new DataSet(); DataTable table = new DataTable("SampleTable"); table.Columns.Add("Id", typeof(int)); table.Columns.Add("Name", typeof(string)); table.Columns.Add("Age", typeof(int)); table.Rows.Add(1, "John", 30); table.Rows.Add(2, "Jane", 25); table.Rows.Add(3, "Bob", 35); dataSet.Tables.Add(table); // Export DataSet to CSV ExportDataSetToCsv(dataSet, "output.csv"); } static void ExportDataSetToCsv(DataSet dataSet, string filePath) { StringBuilder csvContent = new StringBuilder(); // Loop through each table in the DataSet foreach (DataTable table in dataSet.Tables) { // Write the header row (column names) string columnNames = string.Join(",", table.Columns.Cast<DataColumn>().Select(col => col.ColumnName)); csvContent.AppendLine(columnNames); // Loop through each row in the table foreach (DataRow row in table.Rows) { string rowValues = string.Join(",", row.ItemArray.Select(val => $"\"{val.ToString().Replace("\"", "\"\"")}\"")); csvContent.AppendLine(rowValues); } } // Write the CSV content to the file File.WriteAllText(filePath, csvContent.ToString()); Console.WriteLine("Data exported to " + filePath); } }
In this example:
- DataSet: A
DataSet
is created with oneDataTable
containing sample data (ID, Name, Age). - ExportDataSetToCsv: The function loops through each table in the
DataSet
and exports its contents to a CSV file.- It first writes the column names (header).
- Then it loops through each row and writes the values as comma-separated strings, handling any quotes in the data by escaping them with double quotes (
""
).
- File Writing: The content is written to the specified CSV file using
File.WriteAllText
.
You can modify the code to export a DataSet
with multiple tables, or customize the file path as needed.