Convert DataTable to CSV in C#: Easy and Efficient Method

If you're working with data in C#, you may find yourself needing to convert a DataTable to a CSV file. Fortunately, this is a relatively easy and efficient task to accomplish.

First, you'll need to add the following namespaces to your code:

using System.Data;
using System.IO;
using System.Text;

Next, you can use the following code to convert your DataTable to a CSV file:

// Create the CSV file.
var csv = new StringBuilder();

// Add the header row.
var headerRow = string.Join(",", dt.Columns.Cast<DataColumn>().Select(column => column.ColumnName));
csv.AppendLine(headerRow);

// Add the data rows.
foreach (DataRow row in dt.Rows)
{
    var fields = row.ItemArray.Select(field => field.ToString()).ToArray();
    var rowText = string.Join(",", fields);
    csv.AppendLine(rowText);
}

// Save the CSV file.
File.WriteAllText(filePath, csv.ToString());

In this code, "dt" is your DataTable and "filePath" is the path where you'd like to save the CSV file. The code creates a StringBuilder object and uses it to build a CSV string. It then adds the header row by joining the column names with commas and appending the resulting string to the StringBuilder. Finally, it loops through each DataRow in the DataTable, converts the data to strings, joins the fields with commas, and appends the resulting string to the StringBuilder. Once the StringBuilder is complete, the code saves the CSV file to the specified path using the File.WriteAllText() method.

This method is both easy to understand and efficient, making it a great choice for converting DataTables to CSV files in C#.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information