我使用以下代码从unicode string创建csv文件:
context.Response.ContentType = "text/csv";
context.Response.ContentEncoding = System.Text.Encoding.Utf8;
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fundName + ".csv");
context.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
String output ="";
output += "Name, callNumber" + "\n";
String output ="علی,34343555" + "\n";
context.Response.Write(output);
问题是unicode字符无法正确显示“علی”。
感谢任何指南。 问候 阿里
答案 0 :(得分:2)
代码存在一些问题。
context.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
为UTF-32 而不是 UTF-8写入BOM。
输出变量定义了两次。
我建议尝试这个:
context.Response.ContentType = "text/csv";
context.Response.ContentEncoding = System.Text.Encoding.Utf8;
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fundName + ".csv");
String output ="";
output += "Name, callNumber" + "\n";
output +="علی,34343555" + "\n";
context.Response.Write(output);
context.Response.End()
答案 1 :(得分:2)
我宁愿使用streamwriter来使用UTF-8编码来编写unicode字符。 片段:
using (StreamWriter sw = new StreamWriter(new FileStream("c:/Temp.csv", FileMode.Create), Encoding.UTF8))
{
sw.WriteLine(string.Join(",", s));
}
答案 2 :(得分:0)
只需使用它即可编写Unicode CSV文件:
File.WriteAllText("path/to/file.csv", yourString, Encoding.Unicode);
答案 3 :(得分:-1)
Response.Clear();
Response.AppendHeader("Content-Type", "Application/vnd.ms-excel");
Response.ContentEncoding = Encoding.UTF8;
Response.AppendHeader("Content-Disposition", "attachment; filename=filename1.csv");
var data = Encoding.UTF8.GetBytes("your content with chinese characters");
var result = Encoding.UTF8.GetPreamble().Concat(data).ToArray();
var str = Encoding.UTF8.GetString(result);
Response.Write(str);
Response.Flush();
Response.SuppressContent = true;