为什么我的StreamWriter响应输出在Excel中产生垃圾重音但在记事本中看起来很好?

Nea*_*son 4 asp.net excel response character-encoding streamwriter

我正在使用另一个Stack Overflow问题的技术将CSV文件写入Response输出以供用户打开/保存.该文件在记事本中看起来不错,但是当我在Excel中打开它时,重音字符是垃圾.我认为这与字符编码有关,所以我尝试手动将其设置为UTF-8(默认为StreamWriter).这是代码:

// This fills a list to enumerate - each record is one CSV line
List<FullRegistrationInfo> fullUsers = GetFullUserRegistrations();

context.Response.Clear();
context.Response.AddHeader("content-disposition",
                           "attachment; filename=registros.csv");
context.Response.ContentType = "text/csv";
context.Response.Charset = "utf-8";

using (StreamWriter writer = new StreamWriter(context.Response.OutputStream))
{
    for (int i = 0; i < fullUsers.Count(); i++)
    {
        // Get the record to process
        FullRegistrationInfo record = fullUsers[i];

        // If it's the first record then write header
        if (i == 0)
            writer.WriteLine(Encoding.UTF8.GetString(
                Encoding.UTF8.GetPreamble()) + 
                "User, First Name, Surname");

        writer.WriteLine(record.User + "," +
                         record.FirstName + "," +
                         record.Surname);
    }
}

context.Response.End();
Run Code Online (Sandbox Code Playgroud)

有关正确编码文件需要做什么的任何想法,以便Excel可以查看重音字符?

ron*_*ron 7

您可能必须将一个名为Byte-order Mark的UTF-8指示符写入输出的开头,以通知Excel有关UTF-8的信息.愚蠢的Excel.

  • 谢谢罗恩!我使用Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble())在文件的开头写出来,然后处理. (2认同)