Using C# and VSTO, the type of a cell in Excel can be set with the following code:
worksheet.Cells[i, j].NumberFormat = magicString;
, where worksheet
is an object of the Microsoft.Office.Interop.Excel.Worksheet
class, i
is a row number of the cell, j
is a column number of the cell, magicString
is some string defining the type of the cell (note: Excel calls types as format, but below I'm using the word type).
The following magicString
s define the following Excel types:
string magicString = "";
- defines the "General" Excel type;string magicString = "@";
- defines the "Text" Excel type;string magicString = "0%";
- defines the "Percent" Excel type.
The situation is more complicated when I would like to set the "Date" Excel type. The complexity is related to the localization of the Excel and to the localization of the Windows system.
So, for example, I have a Russian version of Excel (in particular, all types are written in Excel in Russian) and my Windows system has the following short-date format: "dd.MM.yyyy" (one can find this setting in Control Panel > Region and Language > Formats). I have an English version of Windows but this plays absolutely no role.
As a result, if I will use the following magicString
in my code, the type of the cell will be set to the short-date type:
string magicString = "ДД.ММ.ГГГГ";
- defines the "Date" (or, more exactly, the "Short-Date") Excel type;
As you can see, here the magicString
is a combination of the Russian letters (Russian - because the Excel is Russian) and of the format set in the Windows settings.
If, instead of this magicString
, I use the magicString
equal to "DD.MM.YYYY" (i.e. the English letters), errors appear.
Thus, if I would want that my Excel add-in would be able to set correctly the "Short-Date" type for all (English, Russian, German and all other) versions of Excel and for all localization settings of Windows, I have to be able to use some universal magicString
, that is independent of two mentioned factors.
As an option, I can read the short-date format from the Windows settings with this code:
string shortDatePattern = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
and then, replace the letters in the obtained shortDatePattern
string with those that correspond to the language of Excel. However, this way seems to me too complicated.
My question is: is there some universal magicString
that is valid for all Excel languages and for all Windows localization settings, like it takes place for other Excel types like "General", "Text", and "Percent"? Or, maybe, someone knows other simple way to reach such an universality?