I use next code to generate .csv file from my logs table.
public ActionResult Index()
{
var records = loggingService.GetLogRecords(model.Since, model.For);
var mainSb = new StringBuilder();
mainSb.Append("Date,User name\n");
foreach (var logRecord in records)
{
mainSb.Append(logRecord.Time.ToString("dd/MM/yyyy hh:mm:ss")).Append(",");
mainSb.Append("\"").Append(logRecord.UserName ?? "").Append("\"").Append(",");
}
return File(Encoding.Unicode.GetBytes(mainSb.ToString()), "text/csv", string.Format("logs.csv"));
}
Usernames contains cyrillic chars, and when I open my .csv file – cyrillic chars is bad displayed. I tried to use UTF8 and UTF32 encodings too. Whan encoding should I use or what changes should I do?
You could use UTF-8 with preamble. Try like this at the end:
Also you seem to be using
\nwhich is not the correct new line separator on Windows and you don’t seem to be appending new lines in your foreach loop, so everything will be on the same line resulting in invalid CSV file. Please, please, please, do not roll your own CSV parser.