我正在使用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可以查看重音字符?