Last active
November 19, 2018 11:01
-
-
Save shammelburg/c19f54929ac13f898e5e to your computer and use it in GitHub Desktop.
Creating CSV File C#
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
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; | |
} |
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
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