Home > Backend Development > C++ > How Can I Efficiently Convert a DataTable to a CSV File in C#?

How Can I Efficiently Convert a DataTable to a CSV File in C#?

Linda Hamilton
Release: 2025-01-15 15:52:44
Original
714 people have browsed it

How Can I Efficiently Convert a DataTable to a CSV File in C#?

C# DataTable to CSV Conversion: Improved Techniques and Debugging

Converting a DataTable to a CSV file requires careful attention to data separation. If your data appears clustered in the first cell of each row, the problem likely stems from incorrect delimiter and line break handling.

The original code, using a StringBuilder, may have a flaw in its row value appending logic. The issue is likely the comma placement—it's added after every value, not just after the last value in each row.

Here's a refined version of the code to address this:

<code class="language-csharp">StringBuilder sb = new StringBuilder();

foreach (DataRow row in dt.Rows)
{
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        sb.Append(row[i].ToString());
        if (i < dt.Columns.Count - 1)
        {
            sb.Append(","); // Add comma only before the last column
        }
    }
    sb.AppendLine(); // Add line break after each row
}

File.WriteAllText("test.csv", sb.ToString());</code>
Copy after login

Alternatively, a more efficient and elegant approach using LINQ (available in .NET 4.0 and later) is shown below:

<code class="language-csharp">StringBuilder sb = new StringBuilder();

IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));

foreach (DataRow row in dt.Rows)
{
    IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
    sb.AppendLine(string.Join(",", fields));
}

File.WriteAllText("test.csv", sb.ToString());</code>
Copy after login

This LINQ-based solution streamlines column and row iteration, employing string.Join for concise delimiter insertion. This method is generally preferred for its readability and efficiency.

The above is the detailed content of How Can I Efficiently Convert a DataTable to a CSV File in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template