Skip to content

Instantly share code, notes, and snippets.

@antodr
Forked from luisdeol/DataExportClass.cs
Created September 23, 2023 23:39
Show Gist options
  • Save antodr/fd285b3969979aa6814771bdfd3ca7ad to your computer and use it in GitHub Desktop.
Save antodr/fd285b3969979aa6814771bdfd3ca7ad to your computer and use it in GitHub Desktop.
Export List of Objects to a Comma-Separated Values (.CSV) file using C#, allowing the export of Entity Framework DbSet to CSV File. An example of use comes within the code.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace DataExportClass
{
class Program
{
public class Employee
{
public string Name { get; set; }
public string Cpf { get; set; }
}
static void Main(string[] args)
{
var employees = new List<Employee>()
{
new Employee
{
Cpf = "1234",
Name = "Luis Felipe"
},
new Employee
{
Cpf = "5678",
Name = "Matheus Guedes"
}
};
ExportData.ExportCsv(employees, "employees");
}
public static class ExportData
{
public static void ExportCsv<T>(List<T> genericList, string fileName)
{
var sb = new StringBuilder();
var basePath = AppDomain.CurrentDomain.BaseDirectory;
var finalPath = Path.Combine(basePath, fileName+".csv");
var header = "";
var info = typeof(T).GetProperties();
if (!File.Exists(finalPath))
{
var file = File.Create(finalPath);
file.Close();
foreach (var prop in typeof(T).GetProperties())
{
header += prop.Name + "; ";
}
header = header.Substring(0, header.Length - 2);
sb.AppendLine(header);
TextWriter sw = new StreamWriter(finalPath, true);
sw.Write(sb.ToString());
sw.Close();
}
foreach (var obj in genericList)
{
sb = new StringBuilder();
var line = "";
foreach (var prop in info)
{
line += prop.GetValue(obj, null) + "; ";
}
line = line.Substring(0, line.Length - 2);
sb.AppendLine(line);
TextWriter sw = new StreamWriter(finalPath, true);
sw.Write(sb.ToString());
sw.Close();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment