How to Export DataTable to CSV using CsvHelper in C#
By FoxLearn 12/10/2024 2:40:00 AM 20.73K
CsvHelper is a popular library for reading and writing CSV files.
How to Export DataTable to CSV using CsvHelper in C#
Drag and drop the DataGridView, Button controls from your Visual Studio toolbox onto your form designer, then design a simple windows forms allows you to export datatable to csv file using CsvHelper in c# as shown below.
Right-clicking on your project, then select Manage Nuget Packages from the Visual Studio.
Next, Search 'CsvHelper', then download and install it.
You can install it using the NuGet Package Manager Console
Install-Package CsvHelper
Once installed, you can use the following code to export a DataTable to a CSV file. CsvHelper is an open source library helps you read and write csv files. It's extremely fast, flexible, and easy to use.
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) { // c# savefiledialog 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) { // csvhelper datatable to csv 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