Date:

Share:

How to Convert a DataTable to CSV in C#

Related Articles

In this article, I am going to explain how to convert the data table to CSV file using c# with examples. I will show you an efficient and easy way to export data from the data table and create a CSV file.

Data is an essential component of any application. An application developer needs to know how to handle data and manipulate it efficiently. The data can be in different formats, such as XML, JSON or CSV. So, in this article, we will discuss how to convert data table to CSV file using C# with an example.

In my previous article, I explained how to convert images to text in c#, what is dependency injection in c#, how to read large text files in batch using c#, the efficient way to write CSV files from datatable, how to convert JSON to datatable or dataset using c# and How to perform CRUD operation using angular 14 with web API, you may want to read.

What is a DataTable?

DataTable is a .NET class used to store data in tabular format. It is similar to a database table, and contains rows and columns. Each column in a DataTable has a specific data type, and each row represents a unique record. A DataTable is an in-memory representation of data and is often used to read and manipulate data from a database or file.

What is CSV?

CSV stands for comma separated values. It is a file format used to store data in plain text format, with each value in a line separated by a comma. CSV files are commonly used to exchange data between different applications.

Why convert DataTable to CSV?

There are several reasons why we might need to convert a DataTable to a CSV file. Some of these reasons are:

  1. Data Backup: It is often necessary to take a backup of the data stored in the DataTable. A CSV file is an ideal format for storing data backups because it is easy to read and can be opened with a text editor.
  2. Exchange of information: CSV files are commonly used to exchange data between different applications. By converting a DataTable to a CSV file, we can easily share the data with other applications.
  3. Data Analysis: CSV files are often used for data analysis purposes. By converting the DataTable to a CSV file, we can easily import the data into data analysis tools such as Excel or Power BI.

Convert Datatable to CSV using C# with example

To convert a DataTable to a CSV file in C#, we can use the StringBuilder class. The StringBuilder class provides methods for adding strings, and is effective when we need to concatenate a large number of strings.

The following code demonstrates how to convert a DataTable to a CSV file using C#:

public static void ConvertDataTableToCsv(DataTable dataTablestring filePath)
        {
            StringBuilder sb = new StringBuilder();
 
            foreach (DataColumn column in dataTable.Columns)
            {
                sb.Append(column.ColumnName + ",");
            }
 
            sb.Remove(sb.Length - 1, 1);
            sb.Append(Environment.NewLine);
 
            foreach (DataRow row in dataTable.Rows)
            {
                foreach (DataColumn column in dataTable.Columns)
                {
                    sb.Append(row[column].ToString() + ",");
                }
 
                sb.Remove(sb.Length - 1, 1);
                sb.Append(Environment.NewLine);
            }
 
            File.WriteAllText(filePath, sb.ToString());
        }

Let’s understand the code step by step:

  1. We declare a static method called ConvertDataTableToCsv that takes two parameters, a DataTable and a file path.
  2. We declare a StringBuilder object named sb. We will use this object to construct the CSV string.
  3. We loop through each column in the DataTable and append the column name to a StringBuilder object, followed by a comma.
  4. We remove the last comma from the StringBuilder object and add a newline character.
  5. We loop through each row in the DataTable and append each value to a StringBuilder object, followed by a comma.
  6. We remove the last comma from the StringBuilder object and add a newline character.
  7. Finally, we write the contents of the StringBuilder object to a file using the File.WriteAllText method.

Using code to convert DataTable to CSV

To use the code to convert a DataTable to a CSV file, we need to create a DataTable object and populate it with data. We can then call the ConvertDataTableToCsv method, providing the DataTable and file path as parameters. Here is an example:

In this example, we create a DataTable object and add three columns (CustomerId, CustomerName, ProductName, and Price) of different data types. Next we will add three rows of data to the DataTable.

// Create a DataTable object
DataTable dataTable = new DataTable();
 
// Add columns to the DataTable
dt.Columns.Add("CustomerId"typeof(int));
dt.Columns.Add("CustomerName"typeof(string));
dt.Columns.Add("ProductName"typeof(string));
dt.Columns.Add("Price"typeof(double));
 
// Add rows to the DataTable
dt.Rows.Add(1, "Nikunj Satasiya""Laptop", 55000);
dt.Rows.Add(2, "Hiren Dobariya""Mouse", 1022);
dt.Rows.Add(3, "Vivek Ghadiya""Pen", 350);
dt.Rows.Add(4, "Dinesh Barad""Laptop", 144000);
dt.Rows.Add(5, "Priya Patel""Pendrive", 650);
dt.Rows.Add(6, "Kishan Kumar""Charger Cable", 302);
 
// Convert the DataTable to a CSV file
ConvertDataTableToCsv(dataTable, "C:\Users\NikunjSatasiya\Desktop\Customers.csv");

Finally, we call the ConvertDataTableToCsv method, passing the DataTable object and the file path (“C:UsersNikunjSatasiyaDesktopCustomers.csv”) as parameters.

The output file (Customers.csv) will contain the following data:

This is a basic example of how to convert a DataTable to a CSV file using C#. You can modify the code to suit your needs, such as adding header and footer lines or changing the delimiter character.

Summary

In this article, we discussed how to convert DataTable to CSV file using C#. We’ve seen that the StringBuilder class is a useful tool for efficiently concatenating strings.

We also discussed why we might need to convert a DataTable to a CSV file, including data backup, data replacement, and data analysis.

By following the code sample provided in this article, you can easily convert a DataTable to a CSV file in your C# application.

badges:

  • c# Create a csv streamwriter file
  • c# library csv
  • c# csv to data table
  • c# csv writer
  • c# dynamic list to csv
  • c# export list to csv file
  • c# export list to csv with headers
  • c# export object to csv
  • c# export to csv
  • c# export to csv from data table
  • c# export to csv:stackoverflow.com
  • c# list to csv nuget
  • c# list to csv string
  • c# Save csv file to folder
  • c# Write a csv file with commas
  • c# write to csv file append
  • Convert data table to csv file c#
  • Convert data table to text file c#
  • Create c# csv file with header
  • Data table to csv r
  • dataset to csv c#
  • Customize csv data table export
  • Customize Excel data table export
  • Data table will export all data
  • Export data table button does not appear
  • Export csv data table
  • Export custom data table data
  • Data table to csv c# csvhelper
  • Data table to csv javascript
  • Export dataframe to csv r mac
  • Export data table to excel javascript
  • fwrite r
  • How to export data from r to excel
  • memory stream to csv file c#
  • list of objects to csv c#
  • r data.table read csv
  • write csv r
  • Write csv r tidyverse
  • Write data table to csv c# streamwriter
  • Example to write.csv
  • write.csv rstudio
  • c# create csv
  • c# create data table
  • c# csv to data table
  • c# data table to csv
  • c# export to csv
  • c# json to csv
  • c# write a csv file
  • c# write to csv
  • Convert a csv file to Excel
  • csv to excel conversion
  • Convert csv to json
  • csv to json javascript conversion
  • Convert csv to sql
  • Convert Excel file to csv
  • Excel to csv conversion
  • Excel to sql conversion
  • Convert file to csv
  • json conversion
  • json file conversion
  • Convert json file to csv
  • Convert a json file to Excel
  • Convert json to csv
  • Convert json to csv
  • Convert json to csv javascript
  • Convert json to excel
  • Convert json to table
  • Convert sql to csv
  • convert to csv file
  • Excel to csv conversion
  • Create a csv
  • Create a csv file
  • create csv file c#
  • Create a csv file from Excel
  • Create a data table
  • csv c#
  • csv converter
  • csv data
  • csv data file
  • csv database
  • csv example
  • csv file
  • Example of a csv file
  • csv excel file
  • csv file format
  • csv file format example
  • csv format
  • Example of csv format
  • csv excel format
  • csv generator
  • csv to datatable c#
  • csv to json
  • csv to json javascript
  • csv to sql
  • csv to table
  • Bile data
  • Date table
  • Example of a data table
  • data to csv
  • data table c#
  • excel csv
  • csv excel file format
  • Excel export to csv
  • Excel to csv file
  • Convert excel to json
  • Converts excel to sql
  • Export excel to json
  • Export json to Excel
  • Export sql table to csv
  • Export to csv
  • sql data format
  • from json to csv
  • Create a csv file
  • javascript csv to json
  • javascript csv export
  • javascript json to csv
  • Convert json file to Excel
  • json file to csv
  • json format converter
  • json to csv
  • json to csv c#
  • json to csv excel
  • json to csv javascript
  • Create a csv file
  • Open a csv file
  • Open the csv
  • Open a csv file
  • Open a csv file in Excel
  • Open the csv in Excel
  • Open a json file in Excel
  • Open the json in Excel
  • sql create table from csv
  • sql export excel
  • Export sql to csv
  • Export sql server to csv
  • sql to csv
  • Converts sql to excel
  • Convert sql to json
  • Table to csv
  • Write to csv
  • Write to a csv file

Source

Popular Articles