.net CSV文件是显示荒谬的字符,而不是中文或韩语

wgxvkvu9  于 2022-12-01  发布在  .NET
关注(0)|答案(1)|浏览(119)

我已经创建了一个通用的方法,下载一个csv文件的任何输入。我面临的问题与中文和韩语字符,因为他们是不同的csv文件。

private IActionResult ReturnCsvFile<T>(IEnumerable<T> users)
        {
            var csvString = new StringBuilder();
            Type typeParameterType = typeof(T);

            var propInfos = typeParameterType.GetProperties(
            BindingFlags.Instance | BindingFlags.Public).OrderBy(x => x.MetadataToken)
                .Select(p => p.GetCustomAttribute<JsonPropertyAttribute>());

            csvString.AppendLine(string.Join(",", propInfos.Select(x => x.PropertyName)));
            var counter = 1;
            foreach (var item in users)
            {
                PropertyInfo[] props = item.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).OrderBy(x => x.MetadataToken).ToArray();
                props[0].SetValue(item, Convert.ChangeType(counter++, props[0].PropertyType, CultureInfo.InvariantCulture), null);
                string commaSeperatedValues = string.Join(",", props.Select(prop => "\"" + Convert.ToString(prop.GetValue(item), CultureInfo.InvariantCulture) + "\""));
                csvString.AppendLine(commaSeperatedValues);
            }
            var test = new UTF8Encoding(false).GetBytes(csvString.ToString());
            return File(test, "text/csv", "UsersList.csv");
        }
qoefvg9y

qoefvg9y1#

问题是:

Excel无法打开没有BOM(字节顺序标记)的Unicode文件。

它会将它们作为Ansi文件打开,这会将unicode字符显示为垃圾。
由于您使用的是Encoding.GetBytes(),因此永远不会有BOM。
若要取得材料表,您必须使用StreamWriter
您可以将最后两行替换为以下内容来解决此问题:

using (MemoryStream ms = new())
{
    using (StreamWriter sw = new(ms, new UTF8Encoding(true)))
    {
        sw.Write(csvString);
    }
}
return File(ms, "text/csv", "UsersList.csv");

现在应该有一个BOM,Excel应该能够正确打开它。

相关问题