Skip to content

Instantly share code, notes, and snippets.

@code-atom
Created May 4, 2017 09:09
Show Gist options
  • Save code-atom/1e7896ffd0c725f5dd6af6d53042f952 to your computer and use it in GitHub Desktop.
Save code-atom/1e7896ffd0c725f5dd6af6d53042f952 to your computer and use it in GitHub Desktop.
CVS File from Generic Collection
public class CsvFileActionResult<T> : System.Web.Mvc.ActionResult
{
public string FileName { get; set; }
public IEnumerable<T> List { get; set; }
protected virtual void Write(IEnumerable<T> list, TextWriter output)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
foreach (PropertyDescriptor prop in props)
{
output.Write(prop.DisplayName); // header
output.Write(",");
}
output.WriteLine();
foreach (T item in list)
{
foreach (PropertyDescriptor prop in props)
{
string value = String.Empty;
DefaultValueAttribute defaultAttribute = GetAttribute<DefaultValueAttribute>(prop);
LimitToAttribute limitToAttribute = GetAttribute<LimitToAttribute>(prop);
if (prop.GetValue(item) != null)
value = prop.Converter.ConvertToString(prop.GetValue(item));
else if (defaultAttribute != null)
value = prop.Converter.ConvertToString(defaultAttribute.Value);
if (limitToAttribute != null)
value = value.limitToSize(limitToAttribute.limitSize);
output.Write(value);
output.Write(",");
}
output.WriteLine();
}
}
public T GetAttribute<T>( PropertyDescriptor prop) where T : Attribute
{
foreach (Attribute att in prop.Attributes)
{
var tAtt = att as T;
if (tAtt != null) return tAtt;
}
return null;
}
public CsvFileActionResult(IEnumerable<T> list, string fileName)
{
List = list;
FileName = fileName;
}
public override void ExecuteResult(ControllerContext context)
{
//Create a response stream to create and write the Excel file
HttpContext curContext = HttpContext.Current;
curContext.Response.Clear();
curContext.Response.AddHeader("content-disposition", "attachment;filename=" + FileName);
curContext.Response.Charset = "";
curContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
curContext.Response.ContentType = "txt/csv";
//Convert the rendering of the grid view to a string representation
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
Write(List, stringWriter);
//Open a memory stream that you can use to write back to the response
byte[] byteArray = Encoding.ASCII.GetBytes(stringWriter.ToString());
MemoryStream memoryStream = new MemoryStream(byteArray);
StreamReader streamReader = new StreamReader(memoryStream, Encoding.ASCII);
//Write the stream back to the response
curContext.Response.Write(streamReader.ReadToEnd());
curContext.Response.End();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment