Last active
September 24, 2019 06:10
-
-
Save tobbbe/c3c416649e5edd007f29eb3df576159d to your computer and use it in GitHub Desktop.
export string to csv file web api umbraco
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 class ExportController | |
{ | |
[HttpGet] | |
public HttpResponseMessage AllUsers() | |
{ | |
var csv = new StringBuilder(); | |
var fileName = $"export {DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss")}.csv"; | |
var result = new HttpResponseMessage(HttpStatusCode.OK); | |
var excelDateTimeFormat = "yyyy-MM-dd HH:mm:ss"; // format datetimes so excel can parse them | |
// headers | |
csv.AppendLine("Name;Id;Last login"); | |
foreach (var user in ListOfUsers) | |
{ | |
csv.AppendLine(string.Format("{0};{1};{2}", | |
ToSafeCsvString(user.Name), | |
ToSafeCsvString(user.Id), | |
ToSafeCsvString(user.LastLoginDate.ToString(excelDateTimeFormat)) | |
)); | |
// ALTERNATIVE way | |
// var columns = new List<string>(); | |
// columns.Add(ToSafeCsvString(user.Name)); | |
// columns.Add(ToSafeCsvString(user.Id)); | |
// columns.Add(ToSafeCsvString(user.LastLoginDate.ToString("yyyy-MM-dd HH:mm:ss"))); | |
// and then | |
// csv.AppendLine(string.Format(GetStringFormat(columns), columns.ToArray())); | |
} | |
// save file to disk | |
//File.WriteAllText(HttpContext.Current.Request.MapPath("~/Content/ass.csv"), csv.ToString(), Encoding.UTF8); | |
// utf-8 with BOM | |
result.Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes(csv.ToString())).ToArray())); | |
result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv"); | |
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = fileName }; | |
return result; | |
} | |
} | |
private string GetStringFormat(List<string> list) | |
{ | |
var sf = ""; | |
for (int i = 0; i < list.Count; i++) | |
{ | |
sf += "{" + i + "};"; | |
} | |
return sf; // returns "{0};{1};{2};..." | |
} | |
private string ToSafeCsvString(string s) | |
{ | |
if (s == null) return ""; | |
// replace " with "" and wrap all whole text with "", so that excel can handle ,;" etc | |
return $"\"{s.Replace("\"", "\"\"")}\""; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment