Last active
May 6, 2024 09:29
-
-
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.
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.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(); | |
} | |
} | |
} | |
} | |
} |
thanks, clear and good!
but to separate into columns, need to use "," and not ";"
header += prop.Name + ", ";
line += prop.GetValue(obj, null) + ", ";
It Works fine! thank you
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you very much for this good information and example.