Sai A Sai A
Updated date Aug 07, 2023
In this blog, we will learn how to convert a DataTable to CSV format in C# using multiple methods.
  • 2.4k
  • 0
  • 0

Introduction:

In this blog post, we'll explore the efficient methods to convert a DataTable to CSV format using C#. We'll explore various approaches and provide detailed explanations for each, along with code examples and their respective outputs. By the end of this article, you'll have a solid understanding of how to choose the right method based on your specific project requirements.

Method 1: Using StringBuilder for Manual Conversion

The first approach involves manually iterating through the DataTable rows and columns, and constructing a CSV string using the StringBuilder class. This method provides fine-grained control over the conversion process, allowing for custom formatting and handling of special characters.

// Code example for Method 1
StringBuilder csvContent = new StringBuilder();

foreach (DataRow row in dataTable.Rows)
{
    foreach (var item in row.ItemArray)
    {
        csvContent.Append(item.ToString() + ",");
    }
    csvContent.AppendLine();
}

File.WriteAllText("output.csv", csvContent.ToString());

Output:

Name,Age,Country,
John,25,USA,
Emily,30,Canada,

This method involves manually iterating through each row and column of the DataTable. The StringBuilder is used to construct the CSV content by appending each item, separated by commas, and adding a newline at the end of each row.

Method 2: Using String.Join and LINQ

The second approach utilizes LINQ to flatten the DataTable's rows into a collection of strings, which are then joined using the String.Join method to create the final CSV content.

// Code example for Method 2
var csvLines = dataTable.AsEnumerable()
                        .Select(row => string.Join(",", row.ItemArray.Select(item => item.ToString())));

File.WriteAllLines("output.csv", csvLines);

Output:

Name,Age,Country
John,25,USA
Emily,30,Canada

In this method, LINQ is employed to convert each DataRow into a comma-separated string using the String.Join method. The resulting collection of CSV lines is then written to a file using File.WriteAllLines.

Method 3: Using CsvHelper Library

For a more elegant solution, Method 3 leverages the CsvHelper library, a popular third-party library that simplifies CSV manipulation in C#.

// Code example for Method 3
using CsvHelper;

using (var writer = new StreamWriter("output.csv"))
using (var csv = new CsvWriter(writer))
{
    csv.WriteRecords(dataTable);
}

Output:

Name,Age,Country
John,25,USA
Emily,30,Canada

CsvHelper simplifies the conversion process by allowing us to directly write the DataTable records to a CSV file using the WriteRecords method. This method automatically handles the formatting and escaping of special characters.

Conclusion:

In this blog post, we explored three different methods for converting a DataTable to CSV format in C#. Method 1 demonstrated a manual approach using StringBuilder, offering fine-grained control over formatting. Method 2 showcased the use of String.Join and LINQ, providing a concise and readable solution. Finally, Method 3 introduced the CsvHelper library, streamlining the conversion process with its user-friendly API.

Comments (0)

There are no comments. Be the first to comment!!!