Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

ActionResult for ASP.NET MVC that returns a CSV file from any list of objects

View CsvActionResult.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Mvc;
 
namespace webnetconf.website.Helpers
{
public class CsvActionResult<T> : FileResult
{
private readonly IList<T> _list;
private readonly char _separator;
 
public CsvActionResult(IList<T> list,
string fileDownloadName,
char separator=',')
: base("text/csv")
{
_list = list;
FileDownloadName = fileDownloadName;
_separator = separator;
}
 
protected override void WriteFile(HttpResponseBase response)
{
var outputStream = response.OutputStream;
using (var memoryStream = new MemoryStream())
{
WriteList(memoryStream);
outputStream.Write(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
}
}
 
private void WriteList(Stream stream)
{
var streamWriter = new StreamWriter(stream, Encoding.Default);
 
WriteHeaderLine(streamWriter);
streamWriter.WriteLine();
WriteDataLines(streamWriter);
 
streamWriter.Flush();
}
 
private void WriteHeaderLine(StreamWriter streamWriter)
{
foreach (MemberInfo member in typeof(T).GetProperties())
{
WriteValue(streamWriter, member.Name);
}
}
 
private void WriteDataLines(StreamWriter streamWriter)
{
foreach (T line in _list)
{
foreach (MemberInfo member in typeof(T).GetProperties())
{
WriteValue(streamWriter, GetPropertyValue(line, member.Name));
}
streamWriter.WriteLine();
}
}
 
 
private void WriteValue(StreamWriter writer, String value)
{
writer.Write("\"");
writer.Write(value.Replace("\"", "\"\""));
writer.Write("\"" + _separator);
}
 
public static string GetPropertyValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null).ToString()??"";
}
 
}
}

Please see revision https://gist.github.com/mcbrided/5306389/revisions to fix null object issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.