Cybercrux

Everything is achievable through technology

csv Export

Helper to CSV export in MVC


public FileContentResult DownloadCSV()
{
return File(new System.Text.UTF8Encoding().GetBytes("Email ID\nDemoEmail@Domain.com\n"), "text/csv", "InvitationTemplate.csv");
}


public class CsvContent : HttpContent
{
private readonly MemoryStream _stream = new MemoryStream();
public CsvContent(CsvFileDescription outputFileDescription, string filename, IEnumerable data)
{
var cc = new CsvContext();
var writer = new StreamWriter(_stream);
cc.Write(data, writer, outputFileDescription);
writer.Flush();
_stream.Position = 0;
Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
Headers.ContentDisposition.FileName = filename;
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
return _stream.CopyToAsync(stream);
}
protected override bool TryComputeLength(out long length)
{
length = _stream.Length;
return true;
}
}

In controller


IEnumerable masterTripList = _obsvMasterRepo.GetObsTrips(vesselName, dateYear, port, obsvCode, obsvTripCode, obsvProgCode, lastModifiedDateYear, lastModifiedBy, statusCode);
IList masterTripModelList = new List();
foreach (MasterObsTrip trip in masterTripList)
masterTripModelList.Add(new MasterObsTripModel(trip));
CsvFileDescription outputFileDescription = new CsvFileDescription
{
SeparatorChar = ',', // comma delimited
FirstLineHasColumnNames = true, // no column names in first record
FileCultureName = "nl-NL" // use formats used in The Netherlands
};
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK) {
Content = new CsvContent (outputFileDescription,
"ObserverTripList.csv",
masterTripModelList);
}
return response;

reference

Leave a comment