Skip to content

Instantly share code, notes, and snippets.

@Tinomuchenje
Created August 30, 2023 07:40
Show Gist options
  • Save Tinomuchenje/697367c6b372011b5518ba0d2b20edb1 to your computer and use it in GitHub Desktop.
Save Tinomuchenje/697367c6b372011b5518ba0d2b20edb1 to your computer and use it in GitHub Desktop.
Converting Datatable items to a csv format
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