In a data grid I’m displaying numeric values formatted using a standard format string, “N02” in this case. When I export this data to excel, I’d like to format the excel column the same. Is there a way to evaluate the “N02” format for the current locale and get the actual format string?
If not, I’m thinking I’d have to try and reconstruct it using NumberNegativePattern, NumberGroupSizes, NumberGroupSeparator, and NumberDecimalSeparator properties of the current NumberFormat but I really don’t like my chances of getting that right for my than my locale/culture.
This is what I want to set for my Excel interop call:
((Range)excelSheet.Columns[columnLetter + “:” + columnLetter, Type.Missing]).NumberFormat = xxxxx;
I’d like xxxxx for both “N” and for “N02”, I know I can use something like this:
“#,##0.00;-#,##0.00” for “N02”
But that’s made the whole thing culture specific.
The problem here is twofold; firstly, Excel interop exposes only a very limited set of functionality when it comes to working with number styles. Secondly, Excel itself pays little attention to culture-specific formatting.
For example, in the Open XML standard for Excel, all of the built-in number format styles are hard-coded (see the ECMA standard document, page 2128). Although different styles are used according to the user’s locale, Excel does not pay attention to any overrides in the user’s regional settings like the .NET Framework’s globalization features do. Even if you were to marry-up the standard numeric format strings with their Excel equivalents (by region), the format could still differ due to the regional settings in Windows.
As flindeberg mentioned in their comment, formatting the cell values as text is the only way to really be sure that the way your numbers are formatted in .NET is how they will be appear in Excel.
Due to the limitations you’re working with, I would suggest targeting an invariant culture when generating spreadsheets, instead of trying to make specialisations for each culture. By sticking to the rules of the invariant culture, you can fairly easily write an algorithm to translate standard numeric format strings into their expanded form, for use with Excel.