【问题标题】:Encode a string with accents and money symbols and returns a FileStreamReturn(MemoryStream) MVC使用重音符号和货币符号对字符串进行编码并返回 FileStreamReturn(MemoryStream) MVC
【发布时间】:2013-05-14 12:54:57
【问题描述】:

我有这个代码:

StringBuilder output = new StringBuilder();

output.AppendLine("Saldo a disposición: 23.15€");

[...]

System.Text.UnicodeEncoding en = new UnicodeEncoding();
byte[] byteArray = en.GetBytes(output.ToString());
MemoryStream stream = new MemoryStream(byteArray);
string filename = Guid.NewGuid().ToString("N").ToUpper() + ".csv";

stream.Flush();
stream.Seek(0, SeekOrigin.Begin);
return new FileStreamResult(stream, "application/vnd.ms-excel") { FileDownloadName = filename};

当我打开文档时,不会出现符号“€”和“disposión”中的重音符号。好像是这样的:

Saldo a disposici�n: 23.15�

有人告诉我怎么做吗?

谢谢!!

【问题讨论】:

  • 用 UTF8 编码会有区别吗?
  • 不,没有区别。 :(

标签: c# asp.net-mvc csv character-encoding stringbuilder


【解决方案1】:

以下对我有用:

string filename = Guid.NewGuid().ToString("N").ToUpper() + ".csv";

MemoryStream stream = new MemoryStream();

StreamWriter output = new StreamWriter(stream, Encoding.UTF8, 2 << 22);
output.WriteLine("Column1,Column2");
output.WriteLine("value for column one,\"Saldo a disposición: 23.15€\"");
output.WriteLine("another row col 1,another row col 2");
output.Flush();

stream.Seek(0, SeekOrigin.Begin);

return new FileStreamResult(stream, "application/octet-stream") { FileDownloadName = filename };

似乎是编码。

http://en.wikipedia.org/wiki/Unicode http://en.wikipedia.org/wiki/UTF-8

【讨论】:

  • 我在 Excel 中总是出错,但如果你用文本编辑器打开它,我会得到格式正确的文本。为什么会这样?
  • 尝试使用 return new FileStreamResult(stream, "application/octet-stream") ?它不是一个 excel 二进制文件。
  • 另外值得确保您的输出符合 CSV 格式的准则:en.wikipedia.org/wiki/Comma-separated_values
  • 我查看了所有内容,并更改了内容类型,而不是您发送给我的内容类型,但仍然是错误的。可能是电脑的任何配置?当我将文件保存在服务器中并打开它时,文件没问题(带有正确的符号和重音符号),但是当我尝试直接下载而不将文档保存在服务器中时失败。
  • 似乎excel对UTF8编码非常敏感。我修改了我的答案,并在一个基本的 mvc 应用程序中对此进行了测试。当您使用专门针对 utf-8 编码的流写入器方法时,它似乎工作正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 2014-01-08
  • 2012-09-04
  • 2014-12-07
  • 1970-01-01
相关资源
最近更新 更多