简体   繁体   中英

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. 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. Do I need to go through every value and convert it?

You can use one of the overloaded versions of Convert.ToDecimal method:

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:

var convertedValue = value.ToString(culture);

You could also use string.Format overload:

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.  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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