Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generic CSV Export using CSVHelper
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CsvHelper;
using BrunoMartinsPro.Data.Interfaces.Utils.CSV;
namespace BrunoMartinsPro.Utils.CSV
{
public class CSVUtils : ICSVUtils
{
/// <summary>
/// Create a CSV file from memory
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <returns></returns>
public MemoryStream CreateCsvStream<T>(List<T> entity)
{
//Create csv in memory
var stream = CreateMemoryStream(entity);
//Return csv
return stream;
}
/// <summary>
/// Create a CSV file from memory
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <returns></returns>
public byte[] CreateCsvByteArray<T>(List<T> entity)
{
//Create csv in memory
var stream = CreateMemoryStream(entity);
//Return csv
return stream.ToArray();
}
/// <summary>
/// Create csv in memory and write contents
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <returns></returns>
private MemoryStream CreateMemoryStream<T>(List<T> entity)
{
//Get current culture delimiter
CultureInfo culture = CultureInfo.CurrentCulture;
string delimiter = culture.TextInfo.ListSeparator;
//Create csv in memory
using (var stream = new MemoryStream())
{
using (var writer = new StreamWriter(stream))
{
//Write object to csv
using (var csv = new CsvWriter(writer, new CsvHelper.Configuration.Configuration { Delimiter = delimiter }))
{
//Write records
csv.WriteRecords(entity);
//Clean csv
writer.Flush();
stream.Flush();
stream.Position = 0;
}
}
return stream;
}
}
}
}
using System.Collections.Generic;
using System.IO;
namespace BrunoMartinsPro.Data.Interfaces.Utils.CSV
{
public interface ICSVUtils
{
MemoryStream CreateCsvStream<T>(List<T> entity);
byte[] CreateCsvByteArray<T>(List<T> entity);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment