为什么我的 StreamWriter Response 输出在 Excel 中产生垃圾重音,但在记事本中看起来很好?
我正在使用另一个堆栈溢出的技术问题将 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 可以查看重音字符,您有什么想法吗?
I'm using a technique from another Stack Overflow question to write a CSV file to the Response
output for a User to Open/Save. The file looks good in Notepad, but when I open it in Excel the accented characters are garbage. I assumed this was something to do with the character encoding, so I tried manually setting it to UTF-8 (the default for StreamWriter
). Here is the code:
// 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();
Any ideas as to what else I would need to do to correctly encode the file so Excel can view the accented characters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能需要在开头写入一个名为 Byte-order Mark 的 UTF-8 指示符用于通知 Excel 有关 UTF-8ness 的输出。愚蠢的Excel。
You may have to write an UTF-8 indicator called Byte-order Mark to the beginning of the output to notify Excel about the UTF-8ness. Silly Excel.