Home >Backend Development >C++ >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>
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>
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!