Excel international date formatting - c++

I am having problems formatting Excel datetimes, so that it works internationally. Our program is written in C++ and uses COM to export data from our database to Excel, and this includes datetime fields.
If we don't supply a formatting mask, some installations of Excel displays these dates as Serial numbers (days since 1900.01.01 followed by time as a 24-hour fraction). This is unreadable to a human, so we ha found out that we MUST supply a date formatting mask to be sure that it displays readable.
The problem - as I see it - is that Excel uses international formatting masks. For example; the UK datetime format mask might be "YYYY-MM-DD HH:MM".
But if the format mask is sent to an Excel that is installed in Sweden, it fails since the Swedish version of the Excel uses "ÅÅÅÅ-MM-DD tt:mm".
It's highly impractical to have 150 different national datetime formatting masks in our application to support different countries.
Is there a way to write formatting masks so that they include locale, such that we would be allowed to use ONE single mask?

Unless you are using the date functionality in Excel, the easiest way to handle this is to decide on a format and then create a string yourself in that format and set the cell accordingly.
This comic: http://xkcd.com/1179/ might help you choose a standard to go with. Otherwise, clients that open your file in different countries will have differently formatted data. Just pick a standard and force your data to that standard.
Edited to add: There are libraries that can make this really easy for your as well... http://www.libxl.com/read-write-excel-date-time.html
Edited to add part2: Basically what I'm trying to get at is to avoid asking for the asmk and just format the data yourself (if that makes sense).

I recommend doing the following: Create an excel with date formatting on a specific cell and save this for your program to use.
Now when the program runs it will open this use this excel file to retrieve the local date formatting from the excel and the specified cell.
When you have multiple formats to save just use different cells for them.
It is not a nice way but will work afaik.
Alteratively you could consider creating an xla(m) file that will use vba and a command to feed back the local formatting characters through a function like:
Public Function localChar(charIn As Range) As String
localChar = charIn.NumberFormatLocal
End Function
Also not a very clean method, but it might do the trick for you.

Related

How to convert imported date variable to the original format in Stata?

My original date variable is like this 19jun2015 16:52:04. After importing, it looks like this: 1.77065e+12
The storage type for the new imported variable is str11 and display format is %11s
I wonder how I can restore it back to date format?
William Lisowski gives excellent advice in his comment. For anyone using date-times in Stata, there is a minimal level of understanding without which confusion and outright error are unavoidable. Only study of the help so that your specific needs are understood can solve your difficulty.
There is a lack of detail in the question which makes precise advice difficult (imported -- from what kind of file? using which commands and/or third party programs?), except to diagnose that your dates are messed up and can only be corrected by going back to the original source.
Date strings such as "19jun2015 16:52:04" can be held in Stata as strings but to be useful they need to be converted to double numeric variables which hold the number of milliseconds since the beginning of 1960. This is a number that people cannot interpret, but Stata provides display formats so that displayed dates are intelligible.
Your example is when converted a number of the order of a trillion but if held as a string with only 6 significant figures you have, at a minimum, lost detail irretrievably.
These individual examples make my points concrete. di is an abbreviation for the display command.
clock() (and also Clock(), not shown or discussed here: see the help) converts string dates to milliseconds since Stata's origin. With a variable, you would use generate double.
. di %23.0f clock("19jun2015 16:52:04", "DMY hms")
1750351924000
If displayed with a specific format, you can check that Stata is interpreting your date-times correctly. There are also many small variations on the default %tc format to control precise display of date-time elements.
. di %tc clock("19jun2015 16:52:04", "DMY hms")
19jun2015 16:52:04
The first example shows that even date-times which are recent dates (~2016) and in integer seconds need 10 significant figures to be accurate; the default display gives 4; somehow you have 6, but that is not enough.
. di clock("19jun2015 16:52:04", "DMY hms")
1.750e+12
You need to import the dates again. If you import them exactly as shown, the rest can be done in Stata.
See https://en.wikipedia.org/wiki/Significant_figures if that phrase is unfamiliar.

Spreadsheets: insert into columns as if a stack

First: I know this would be much easier if it was a .CSV but that is not possible (I'd 'a written the code in the time I wrote this post).
I want to insert numbers given by the user along with a time-stamp into a spreadsheet. There will be a graph in the spreadsheet that automatically generates based on columns a and b, hence the need to not be a .CSV. Column A holds Double-Floats of range 0 through 500 and Column B holds Date and Time information. Inserted rows must be at the top, thus pushing all existing data down by one row, each time.
I've been writing this manually and I think its time to stop doing that. I don't really care what language it is done in, but I would prefer C/C++ using at most the boost libraries. All libraries MUST be open-source. OS is Linux and input should from terminal or at least be given to the program as a parameter, such that the user's input could be piped into the program.
I found this, but I'm not sure if it is the best method as I'm not necessarily locked into python.
Insert row into Excel spreadsheet using openpyxl in Python
Thanks for any and all help.
Have you tried this? A C library that read Excel (xls) files: http://libxls.sourceforge.net.
Hope this meet your need.
An alternative: http://www.libxl.com, more powerful but not open source.

Setting Excel NumberFormat for Dates ignoring the locale in native C++

I'm using Excel COM automation from native C++. My goal is to set the NumberFormat of a range for dates. The Problem is, the format string Excel expects depends on the user's locale.
Example:
If the locale is english i have to set the NumberFormat to "dd.mm.yyyy"
If the locale is german i need to use "TT.MM.JJJJ" to get the same result.
I'v found a lot of solutions for .NET, unfortunately i don't have that luxury. The usual solution was to temporarily set the locale of the the Excel thread to english, but it doesn't seem possible with native C++.
I could read the default system locale and then hardcode different format strings, but this won't work as soon as someone uses a locale i haven't included explicitely, so this is a bad solution.
So, how do i solve this problem so it works no matter which locale is used?
One possible solution is to use the system time formatter (like: _tcsftime, strftime, wcsftime) to format the date/time structure to the locale of the running system. Since both your program and excel is expected to run on the same PC, it should work properly without even knowing how the local date/time string look like.
As a fall-back solution, you may have to provide a series of hard-coded format string and/or a user-manually-entered string in the option-configuration section of your program, just in case the default locale format fails.
Additional informations after first reply comment from OP: --------------
locale setting affect the text-display presentation of a datetime-binary-object in the UI only. Such datetime-binary-object is alway stored as a binary structure in a very consistent way, irregardless of locale setting even in its each different contexts, be it in Excel (Date/Time format cell), C++ (various structure depends on api), VisualBasic (Variant).
So if your intention is to export the datetime binary structure to excel, not as a strng, you can alway use the "variant" type to store the date value as excel-automation uses the IDispatch interface. You can forget about the locale setting totally.
Adding of code fragment to export datetime variant and format the cell by code: ----------------
I am using MFC so the the code is very simple, you may have to convert to winapi youself
_Application app;
if (!app.CreateDispatch("Excel.Application"))
{ AfxMessageBox("Cannot start Excel !");
return;
}
app.SetVisible(TRUE);
COleVariant VOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
Workbooks objbooks = app.GetWorkbooks();
_Workbook objbook = objbooks.Add(VOptional);
Worksheets objsheets = objbook.GetWorksheets();
_Worksheet objsheet = objsheets.GetItem(COleVariant((short)1));
// get current date time
COleDateTime timeCurrent = COleDateTime::GetCurrentTime();
// setting date values
Range range;
range = objsheet.GetRange(COleVariant("A2"), COleVariant("B3"));
range.SetValue(COleVariant(timeCurrent));
// range.SetNumberFormat(COleVariant("dd/mm/yyyy"));
range.SetNumberFormat(COleVariant("dddd, mmmm dd, yyyy"));
AfxMessageBox("Done...");

Number formatting in pivot table with Aspose.Cells

I am creating a pivot table in excel sheet by aspose.cells. I want the values to be formatted as Accounting, with a symbol, a comma and 2 decimal places. Is this possible with aspose.cells? Please suggest how to do this with Aspose.Cells and c#.
If you need Accounting number formatting for the PivotField, you may try to use the following numeric formatting using PivotField.Number attribute instead.
pivotTable.DataFields[0].Number = 43; //You may also try it with 44 if it suits your needs.
Alternatively you may try to use the following formatting string for NumberFormat custom attribute of PivotField. You may also check in MS Excel to get your desired custom strings to try with NumberFormat property.
_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(#_)
If you still face any confusion/issue, can you please share the sample Excel file in which you may manually set the desired number formatting for the Pivot Table fields in MS Excel, and share the file with us, so that we can test the scenario at our end.
Furthermore, can you please share the code/sample application with the template files (input, output and expected output file etc.). The files can also be shared in Aspose.Cells product support forum.
Please try using PivotField.NumberFormat property to specify his desired formatting, see the code segment below for reference:
//Specify the number formatting to the first data field added.
pivotTable.DataFields[0].NumberFormat = "$#,##0.00";
Moreover, we also recommend you use our latest version of Aspose.Cells for .NET 7.4.0 in which we made some more enhancements regarding PivotTables.
PS, I am working as Support developer / Technical Evangelist at Aspose.

use uno (openoffice api) to open spreadsheet *without* recalculation

I'm using pyuno to read an excel spreadsheet (running on linux.) Many cells have formulas referring to addins that are, obviously, not available. However the cell values are what I want.
But when I load and read the sheet, it seems those formulas are being evaluated and thus the values are being overwritten with errors.
I've tried several things, none of which have worked:
set flags AutomaticCalculation=False, MacroExecutionMode=NEVER_EXECUTE in the call to desktop.loadComponentFromURL
call document.enableAutomaticCalculation(False) on the loaded document
Any suggestions?
If formluas aren't a matter, you might circumvent the problem by processing a copy of your spreadsheet in which only the values (not the formulas) are present.
To achieve this quickly, select the whole sheet content, copy, special paste; then remove everything except "value". Save to a new file (make sure you don't overwrite the original file or every formula will be lost!). Your script should then be able to process this file.
This is an ugly solution, as there must be a way to do it programmaticaly.
Calc does not yet support using the cached results after loading the document. Libreoffice Calc does now use cached results for xls documents. The results are also stored in ods but are ignored while loading the document and the formula result is evaluated by compiling and interpreting the saved formula.
There are some plans to add this for ods and xlsx too but there are many ods producers out there writting incorrect results in the file. So till now the only solution is to have a second version of the document only saving the results (or implementing it inside calc).