在C#中使用CsvHelper在不同的区域性将csv解析为十进制 [英] Parse csv to decimal on different cultures using CsvHelper in c#
问题描述
CsvHelper在c#中解析小数的问题.
Problem with parsing decimals by CsvHelper in c#.
我创建了一个从byte []而非文件中获取csv文件的类,它可以正常工作.
I created a class that get csv file from byte[] istead of file, and it works correctly.
public static List<Topic> GetAll(byte[] attachmentBytes)
{
using (Stream stream = new MemoryStream(attachmentBytes))
{
using (var reader = new StreamReader(stream, Encoding.GetEncoding(1252), true))
{
using (var csv = new CsvReader(reader))
{
csv.Configuration.Delimiter = ";";
csv.Configuration.HasHeaderRecord = true;
csv.Configuration.CultureInfo = CultureInfo.InvariantCulture;
return csv.GetRecords<Topic>().ToList();
}
}
}
}
就像您可以看到我添加的类一样,将csv映射到对象:
Like you can see I added class to map csv to object:
public class Topic
{
[Name("ID")]
public int Id { get; set; }
[Name("description")]
public string Description { get; set; }
[Name("DecimalPTS")]
public decimal? DecimalPts { get; set; }
}
这就是我的示例csv数据的样子.
And this is how my example csv data looks like.
ID;description;DecimalPTS
1;singing;0,6
2;speaking;2,6
3;working;3,3
但是此解决方案会产生
CsvHelper.TypeConversion.TypeConverterException : The conversion cannot be performed.
Text: '0,6'
MemberType: System.Nullable`1[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
当我替换时,只需执行Replace(',','.');输入时,通过区域设置测试通过,但在我的服务器上测试失败(好像我在服务器上具有不同的区域性语言设置
When I replaced just do Replace(',','.'); on input, localy test pass, but on my server test fails (seems like I have different culture localy, and on the server)
我试图解决的问题:
- 我添加了
csv.Configuration.CultureInfo = CultureInfo.InvariantCulture;
- 我使用了
7.1.1
CSV版本,但更改为12.1.2
,并且仍然存在相同的错误
- I added
csv.Configuration.CultureInfo = CultureInfo.InvariantCulture;
- I used
7.1.1
CSV Version, but changed to12.1.2
, and still the same error
不幸的是,没有任何帮助.
Unfortunately, nothing helped.
推荐答案
尝试将您的文化设置为 de-DE
Try to set your culture to de-DE
csv.Configuration.CultureInfo = new CultureInfo("de-DE");
如果您的应用程序可以运行,您还可以再做一个技巧
You can do one more trick that, if your application works on
- 本地,那么您可以将区域性设置为
zh-CN
,如果位于 上 - 服务器,然后您可以将区域性设置为
de-DE
.
- local then you can set culture to
en-US
and if it's on a - server then you can set culture to
de-DE
.
反之亦然.
演示:
var bytes = File.ReadAllBytes(@"Path to your csv file");
List<Topic> list = GetAll(bytes);
//Print list item to console
foreach (var item in list)
{
Console.WriteLine($"ID: {item.Id}\t Description: {item.Description}\t DecimalPTS: {item.DecimalPts}");
}
输出:
这篇关于在C#中使用CsvHelper在不同的区域性将csv解析为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!