Skip to content

Instantly share code, notes, and snippets.

@luisdeol
Last active May 6, 2024 09:29
Show Gist options
  • Save luisdeol/c2c276796a92c8e3246ce2cd3e17e1df to your computer and use it in GitHub Desktop.
Save luisdeol/c2c276796a92c8e3246ce2cd3e17e1df 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();
}
}
}
}
}
@SimsarCode
Copy link

Thank you very much for this good information and example.

@yaelhasson
Copy link

thanks, clear and good!
but to separate into columns, need to use "," and not ";"
header += prop.Name + ", ";
line += prop.GetValue(obj, null) + ", ";

@jakib01
Copy link

jakib01 commented Dec 8, 2022

It Works fine! thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment