Though this question is asked several times by many people, but again I cannot generate the required CSV file in a proper text. I am creating a CSV file which characters are set in Japanese language. Whenever I generate a CSV file, it is not exporting it in proper encoding. I want it to make it readable in a excel sheet. It is showing correct data while debugging and also notepad is displaying correct csv but while when I read the file from Excel, all text get messed up.
Here is my code:
private void GenerateCSV(string[][] value)
{
string attachment = "attachment; filename=CreatedCSV.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
string delimiter = ", ";
int length = value.GetLength(0);
StringBuilder sb = new StringBuilder();
for (int index = 0; index < length; index++)
sb.AppendLine(string.Join(delimiter, value[index]));
HttpContext.Current.Response.Write(sb.ToString());
HttpContext.Current.Response.End();
}
I tried implementing unicode too but it also did not help. What am I missing here?
Your source string might be incorrectly encoded. We used your code and it works with special characters but our string builder is encoded in UTF8 using this code:
byte[] buffer = Encoding.UTF8.GetBytes(DataFeedCSV.ToString());
StringBuilder sb = new StringBuilder();
sb.Append("pröva-Testing");
sb.Append("\r\n");
var data = Encoding.UTF8.GetBytes(sb.ToString());
var result = Encoding.UTF8.GetPreamble().Concat(data).ToArray();
return File(result, "application/csv", "foo.csv");
With these lines, I think the Excel will be able to encode it using UTF-8 as it knows it is a utf8-encoded csv
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.