Skip to content

Instantly share code, notes, and snippets.

@shammelburg
Last active November 19, 2018 11:01
Show Gist options
  • Save shammelburg/c19f54929ac13f898e5e to your computer and use it in GitHub Desktop.
Save shammelburg/c19f54929ac13f898e5e to your computer and use it in GitHub Desktop.
Creating CSV File C#
public string ComplyWithCSV(string sentense)
{
if(!string.IsNullOrEmpty(sentense))
{
var stripped = sentense.Replace("\"", "\"\""); // Replaces a " with ""
sentense = "\"" + stripped + "\""; // Add " to start and end to allow ,
}
return sentense;
}
public void CreateCsvFile()
{
using (StringWriter sw = new StringWriter())
{
// Gets collection from _repository
var rows = _repo.Get_Data();
string[] headers = { "Column1", "Column2", "Column3", "Column4" };
var fileName = "MyCsvFile";
sw.WriteLine(String.Join(",", headers));
foreach (var column in rows)
{
sw.WriteLine(String.Join(",", column.Prop1, column.Prop2, column.Prop3, column.Prop4));
}
HttpContext.Response.ClearContent();
HttpContext.Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".csv");
HttpContext.Response.ContentType = "application/csv";
HttpContext.Response.Write(sw.ToString());
HttpContext.Response.End();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment