简体   繁体   English

仅为导出设置文化信息

[英]Set culture info for export only

I am interested in exporting some data (mostly numbers) into an Excel and I need it to be in the US format (ie 1,234,567.89) no matter what is the current culture of the user. 我有兴趣将一些数据(主要是数字)导出到Excel中,无论用户当前的文化是什么,我都需要它采用美国格式(即1,234,567.89)。 I don't want to change the culture for the whole application. 我不想改变整个应用程序的文化。 I just need to make sure the numbers will be in the right format. 我只需要确保数字格式正确。 I've tried setting the culture for the current thread, but it seems it changes the culture for the whole application. 我已经尝试为当前线程设置文化,但它似乎改变了整个应用程序的文化。 Any help will be appreciated. 任何帮助将不胜感激。

Edit My data will be in DataTable. 编辑我的数据将在DataTable中。 Do I need to go through every value and convert it? 我是否需要通过每个价值并转换它?

You can use one of the overloaded versions of Convert.ToDecimal method: 您可以使用Convert.ToDecimal方法的重载版本之一:

var culture = new CultureInfo("en-US"); 
var convertedValue = Convert.ToDecimal(value, culture);

In case you need to have a string you could use one of the ToString overloads, for example: 如果您需要一个字符串,您可以使用其中一个ToString重载,例如:

var convertedValue = value.ToString(culture);

You could also use string.Format overload: 您还可以使用string.Format重载:

String.Format(culture , "{0}", value);

And if you want to make it protected against incorrect values: 如果你想保护它免受不正确的值:

if (!decimal.TryParse(value, NumberStyles.Any, culture , out convertedValue ))
{
   //the code in case the value could not be parsed.  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM