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

时间:2009-09-30 09:33:17

标签: asp.net excel character-encoding response streamwriter

我正在使用another Stack Overflow question中的一项技术将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();

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

1 个答案:

答案 0 :(得分:7)

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