使用c#在csv导出中不显示Unicode字符

时间:2018-03-08 13:09:08

标签: c# csv unicode unicode-string

如果我只将字符串作为输入

,以下代码工作正常
Response.ContentType = "text/csv";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.AddHeader("Content-Disposition", "attachment; filename=WaitingForApproval_" + ".csv");

            String output = "";
            output += "Name, callNumber" + "\n";
            output += "잘 지냈어요?,34343555" + "\n";
            Response.Write(output);
            Response.End();


            using (StreamWriter sw = new StreamWriter(new FileStream("c:/Temp.csv", FileMode.Create), Encoding.UTF8))
            {
                sw.WriteLine(_exportedCSV);
            }

但是当我尝试从代码生成字符串时,在导出csv之后它不适合我,它显示错误的字符而不是原始 -

    string dataCSV = GenerateCSV();

  using (StreamWriter sw = new StreamWriter(new FileStream("c:/Temp.csv", FileMode.Create), Encoding.UTF8))
            {
                sw.WriteLine(dataCSV);
            }


public string GenerateCSV()
{

 StringBuilder sb = new StringBuilder();

            string Value = string.Empty;
            sb.Append("sep=;");
            sb.Append("\r\n");

// some logic to get string

  return Convert.ToString(sb);

}

我在调试模式下从上面的代码得到的实际字符串 -

sep=; Country;Korea;Name;잘 지냈어요?(HWR);

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试在GenerateCSV

StringBuilder内进行操作
 Encoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(mystring));

更具体的回报如 -

  return Encoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(sb));