Created
February 25, 2015 23:23
-
-
Save josephrodriguez/48b5f507b754c5211005 to your computer and use it in GitHub Desktop.
The CsvExporter class allows exporting data to a csv file, using generic methods and reflection.
This file contains 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.Data.SqlTypes; | |
using System.IO; | |
using System.Linq; | |
using System.Reflection; | |
using System.Text; | |
namespace Example.Export.CSV | |
{ | |
public class CsvExporter : IDisposable | |
{ | |
private List<string> _headers; | |
private List<Dictionary<string, object>> _rows; | |
public CsvExporter() | |
{ | |
_headers = new List<string>(); | |
_rows = new List<Dictionary<string, object>>(); | |
} | |
public void AddRow<T>(T element) | |
{ | |
IList<PropertyInfo> properties = typeof(T).GetProperties(); | |
var headers = properties | |
.Select(p => p.Name) | |
.Where(h => !_headers.Contains(h)); | |
_headers.AddRange(headers); | |
var row = properties.ToDictionary( | |
property => property.Name, | |
property => property.GetValue(element)); | |
_rows.Add(row); | |
} | |
public void AddRows<T>(IEnumerable<T> elements) | |
{ | |
foreach (var element in elements) | |
AddRow(element); | |
} | |
private string Encode(object value) | |
{ | |
if (value == null) | |
return string.Empty; | |
if (value is INullable && ((INullable)value).IsNull) | |
return string.Empty; | |
if (value is DateTime) | |
{ | |
var datetime = (DateTime) value; | |
return datetime.ToString("MM/dd/yyyy"); | |
} | |
var result = value.ToString(); | |
if (result.Contains(",") || result.Contains("\"")) | |
result = '"' + result.Replace("\"", "\"\"") + '"'; | |
return result; | |
} | |
public string Export() | |
{ | |
var sb = new StringBuilder(); | |
// The headers | |
foreach (var header in _headers) | |
sb.Append(FormatCamelCase(header)) | |
.Append(","); | |
sb.AppendLine(); | |
// The rows | |
foreach (var row in _rows) | |
{ | |
foreach (var header in _headers) | |
sb.Append(row.ContainsKey(header) ? Encode(row[header]) : string.Empty) | |
.Append(","); | |
sb.AppendLine(); | |
} | |
return sb.ToString(); | |
} | |
public void ExportToFile(string path) | |
{ | |
File.WriteAllText(path, Export()); | |
} | |
public byte[] ExportToBytes() | |
{ | |
return Encoding.UTF8.GetBytes(Export()); | |
} | |
public void Dispose() | |
{ | |
_headers = null; | |
_rows = null; | |
} | |
private string FormatCamelCase(string s) | |
{ | |
var b = new StringBuilder(); | |
int j = 0; | |
for (int i = 0; i < s.Length; i++) | |
{ | |
b.Append(s[i]); | |
if (char.IsUpper(s[i])) | |
b.Insert(i + j++, ' '); | |
} | |
return b.ToString().TrimStart(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment