我正在使用 Microsoft 的以下示例来创建 csv 格式化程序 http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters
但是,尽管指定了编码,当我在 Excel 中打开 csv 文件时,像 œ 这样的特殊字符仍无法正确呈现。但在其他应用程序中看起来还不错,包括常规记事本。
public MyCsvFormatter(MediaTypeMapping mediaTypeMapping)
{
MediaTypeMappings.Add(mediaTypeMapping);
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/csv"));
SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
SupportedEncodings.Add(Encoding.GetEncoding("iso-8859-1"));
}
public override void WriteToStream(Type type, object value, Stream writeStream, HttpContent content)
{
Encoding effectiveEncoding = SelectCharacterEncoding(content.Headers);
using (var writer = new StreamWriter(writeStream,effectiveEncoding))
{
// write content
}
}
¢ 呈现为 â,因此其中似乎有一个仅在 Excel 中显示的额外字符。
最佳答案
尝试将字节顺序标记写入流中的第一个记录:
byte[] BOM = new byte[] { 0xef, 0xbb, 0xbf };
同时使用 UTF32 而不是 UTF8 可能会有所帮助。
关于c# - 使用 WEB API 媒体格式化程序时,特殊字符在 Excel 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21684475/