我使用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中。
答案 0 :(得分:2)
尝试将字节顺序标记写为流中的第一条记录:
byte[] BOM = new byte[] { 0xef, 0xbb, 0xbf };
同样使用UTF32而不是UTF8可能会有所帮助。