Created
August 30, 2023 07:40
-
-
Save Tinomuchenje/697367c6b372011b5518ba0d2b20edb1 to your computer and use it in GitHub Desktop.
Converting Datatable items to a csv format
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Data; | |
using System.IO; | |
using System.Text; | |
public static class Extensions | |
{ | |
public static string ToCSV(this DataTable table) | |
{ | |
var result = new StringBuilder(); | |
for (int i = 0; i < table.Columns.Count; i++) | |
{ | |
result.Append(table.Columns[i].ColumnName); | |
result.Append(i == table.Columns.Count - 1 ? "\n" : ","); | |
} | |
foreach (DataRow row in table.Rows) | |
{ | |
for (int i = 0; i < table.Columns.Count; i++) | |
{ | |
result.Append(row[i].ToString()); | |
result.Append(i == table.Columns.Count - 1 ? "\n" : ","); | |
} | |
} | |
return result.ToString(); | |
} | |
} | |
public class Program | |
{ | |
public static void Main() | |
{ | |
DataTable table = new DataTable(); | |
table.Columns.Add("Name"); | |
table.Columns.Add("Age"); | |
table.Rows.Add("John Doe", "45"); | |
table.Rows.Add("Jane Doe", "35"); | |
table.Rows.Add("Jack Doe", "27"); | |
string csv = table.ToCSV(); | |
File.WriteAllText("output.csv", csv); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment