Conversion of DataTable to CSV in C#
When saving DataTable data to a CSV file, you may encounter issues with incorrect data separation. Solutions are provided below:
Consider the following code:
<code class="language-csharp">StringBuilder sb = new StringBuilder(); foreach (DataColumn col in dt.Columns) { sb.Append(col.ColumnName + ','); } sb.Remove(sb.Length - 1, 1); sb.Append(Environment.NewLine); foreach (DataRow row in dt.Rows) { // ... (此处代码仅写入每一行的第一个单元格数据) ... } File.WriteAllText("test.csv", sb.ToString());</code>
The CSV file created by the above code only contains data for the first cell of each row. To solve this problem, a more robust approach can be used:
.NET 3.5 and above
<code class="language-csharp">StringBuilder sb = new StringBuilder(); string[] columnNames = dt.Columns.Cast<DataColumn>().Select(column => column.ColumnName).ToArray(); sb.AppendLine(string.Join(",", columnNames)); foreach (DataRow row in dt.Rows) { string[] fields = row.ItemArray.Select(field => field.ToString()).ToArray(); sb.AppendLine(string.Join(",", fields)); } File.WriteAllText("test.csv", sb.ToString());</code>
.NET 4.0 and above
For .NET 4.0 and above, the code can be further simplified:
<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>
Handling special characters
If you need to handle special characters (such as double quotes) in the data field, you can modify the loop block in the code:
<code class="language-csharp">foreach (DataRow row in dt.Rows) { IEnumerable<string> fields = row.ItemArray.Select(field => string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\"")); sb.AppendLine(string.Join(",", fields)); }</code>
Additionally, to avoid large documents in memory, the CSV content can be written line by line instead of writing the entire document at once.
The above is the detailed content of How to Efficiently Convert a DataTable to a CSV File in C#?. For more information, please follow other related articles on the PHP Chinese website!