导出CSV文件的编码问题 [英] Problem with encoding exporting a CSV file

查看:51
本文介绍了导出CSV文件的编码问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Asp.net mvc生成CSV文件,但是使用葡萄牙语使用特殊字符时遇到了问题.我正在使用以下代码返回文件:

I'm using Asp.net mvc to generate a CSV file, but I'm having problems with special characters in portuguese language. I'm using the following code to return the file:

public FileContentResult RelMatriculas(RelRematriculaVM model)
{
    string fileContent = GenerateTheFile();
    Response.Charset = "utf-8";
    Response.ContentEncoding = Encoding.UTF8;
    return File(new UTF8Encoding().GetBytes(fileContent), "text/csv", "RelMatriculas.csv");
}

我将utf8设置为编码,但是当保存文件并尝试在Excel中打开文件时,我看到的是垃圾字符,而不是特殊字符.

I'm setting utf8 as the encoding, but when a save the file and try to open it in Excel, I see junk characters instead of the special ones.

如果我只是在记事本中打开文件并保存,然后在excel上再次打开,则可以正确显示字符.我是否缺少将文件输出为UTF8的内容?

If I just open the file in notepad and save it, then open it again on excel, is show the characters correctly. Am I missing something to output the file as UTF8?

推荐答案

问题是Excel需要BOM.来自此SO答案:

The problem is Excel expects BOM. From this SO answer:

var data = Encoding.UTF8.GetBytes(fileContent);
var result = Encoding.UTF8.GetPreamble().Concat(data).ToArray();
return File(result, "text/csv", "RelMatriculas.csv");

这篇关于导出CSV文件的编码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆