[英]ASp.net core IActionResult csv encoding problem
I have a problem when trying to save a csv file though an IActionResult.尝试通过 IActionResult 保存 csv 文件时遇到问题。 Special characters like åøæ will not be shown properly when opening the csv file.
打开 csv 文件时,诸如 åøæ 之类的特殊字符将无法正确显示。 I have tried a lot of different approaches, but nothing seems to work.
我尝试了很多不同的方法,但似乎没有任何效果。 My latest attempt was trying to use the CsvHelper library but doesn't seem to work neither.
我最近的尝试是尝试使用 CsvHelper 库,但似乎也不起作用。 Here is my latest attempt.
这是我最近的尝试。
byte[] result;
await using (var memoryStream = new MemoryStream())
await using (var streamWriter = new StreamWriter(memoryStream, new UTF8Encoding(true)))
{
var csvWriter = new CsvWriter(streamWriter, CultureInfo.InvariantCulture);
csvWriter.Configuration.Delimiter = ";";
await csvWriter.WriteRecordsAsync(data);
await streamWriter.FlushAsync();
result = memoryStream.ToArray();
}
return new FileStreamResult(new MemoryStream(result), "text/csv")
{ FileDownloadName = $"data.csv" };
I hobe someone can help me, thanks in advance.我希望有人可以帮助我,提前致谢。
As far as I know, this issue is related with Excel not asp.net core application.据我所知,此问题与 Excel 而非 asp.net 核心应用程序有关。 We could set the download file format to use
utf-8
, but excel doesn't open it with right format.我们可以将下载文件格式设置为使用
utf-8
,但 excel 无法以正确的格式打开它。
You could open your csv file and find it shows as below:你可以打开你的 csv 文件,发现它显示如下:
But excel shows like this:但是excel显示如下:
To force excel to show the special character, you should follow below steps:要强制excel显示特殊字符,您应该按照以下步骤操作:
1.Open Excel and new a empty excel 1.打开Excel新建一个空的excel
2.Import the data using Data-->Import External Data --> Import Data 2.导入数据使用Data-->Import External Data --> Import Data
3.Select the file type of "csv" and browse to your file 3.选择“csv”文件类型并浏览到您的文件
4.In the import wizard change the File_Origin to "65001 UTF" (or choose correct language character identifier) 4.在导入向导中将 File_Origin 更改为“65001 UTF”(或选择正确的语言字符标识符)
5.Change the Delimiter to comma 5.将分隔符改为逗号
6.Select where to import to and Finish 6.选择要导入到的位置并完成
Generate csv codes:生成csv代码:
List<Student> students = new List<Student>
{
new Student { Id = 1, FirstName = "éåæÉà;some other value", LastName = "Kanjilal" },
new Student { Id = 2, FirstName = "Steve", LastName = "Smith" },
new Student { Id = 3, FirstName = "Anand", LastName = "Narayaswamy"}
};
try
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendLine("Id,FirstName,LastName");
foreach (var student in students)
{
stringBuilder.AppendLine($"{student.Id}, { student.FirstName},{ student.LastName}");
}
return File(Encoding.UTF8.GetBytes
(stringBuilder.ToString()), "text/csv;charset=utf-8", "student.csv");
}
catch
{
return Error();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.