我已经创建了一个通用的方法,下载一个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");
}
1条答案
按热度按时间qoefvg9y1#
问题是:
Excel无法打开没有BOM(字节顺序标记)的Unicode文件。
它会将它们作为Ansi文件打开,这会将unicode字符显示为垃圾。
由于您使用的是
Encoding.GetBytes()
,因此永远不会有BOM。若要取得材料表,您必须使用
StreamWriter
。您可以将最后两行替换为以下内容来解决此问题:
现在应该有一个BOM,Excel应该能够正确打开它。