display a timespan in excel - c#

I have a timespan stored as a varchar in sql in the format of totalhours-totalminutes-totalseconds.
Now I have to export that information into excel.
The problem I'm having is that I can not for the life of me find a format within excel that will display this information correctly. Is there a way in which this information can be displayed correctly? I am using XLS in C# to output this info.
Sample input: 48:00:11
Sample output: 1900/02/17 12:11:00 AM or 48.0076388888889

For formatting, you need to set a custom time format:
[h]:mm:ss
...which will show numbers of hours for durations longer than 24 hours. If you type "48:00:11" into an Excel cell, it will create that custom format for you (at least, it did in Excel 2007 on my machine just now). Removing formatting shows the value to be the expected double (which all non-strings are): 2.000127, which is the number of days (with time as fraction) for the duration.
Putting that string value into a worksheet from C# may have a different outcome: I suspect so from the 48.007638... value you obtained. Since you have C# at your disposal I would be inclined to calculate the timespan as a number of days prior to pushing the value to Excel, then formatting as above.

Related

Reading Time HH:mm:ss from excel cell in c#

I need to extract the time from an excel file. The time in excel is expressed in hours:minutes:seconds. The c# code i have that reads the time is:
DateTime dt = DateTime.Parse(worksheet.Cells[row, 3].Value.ToString());
string GetTime = String.Format("{0:t}", dt);
This code works perfect with one file but when i insert another similar file it does not reads the time. Does anyone know why this happens.
Excel table that DOES read the time:
Id
Date
Time
1
18/11/2022
11:51:00
Excel table that DOES NOT read the time:
Id
Date
Time
1
08/08/2022
06:54:00
Excel supports dates natively. Dates are stored in binary form (specifically a floating point number), not as text. They have no format. How they're displayed depends on the cell's numeric format and the end user's locale settings, but the actual value remains binary.
Even when you see a time text in a field, the underlying value is a DateTime whose numeric style shows only the time part. You can test that by changing the cell's numeric style to a full date time or number.
All Excel libraries will load Excel dates as .NET DateTime values. If the Excel sheet contains actual dates, Value is already a DateTime. To get its time part use the DateTime.TimeOfDay property.
For example :
TimeSpan time = ((DateTime)worksheet.Cells[row, 3].Value).TimeOfDay;
I found the solution you have to use FromOADate to get the correct format.
DateTime dt = DateTime.FromOADate((double)worksheet.Cells[row, 3].Value);

Date format problem in C#? While retrieving data from Excel

Below is the image of my code please have a look on it.
I am trying to retrieve data from excel sheet and storing it into database table through SQL bulkcopy.
Error:
The date format is 05-01-2019; it is inserted as 2019-05-01 (database) incorrectly - correct date is 2019-01-05.
When date is greater than 12 it stores in correct format.
2019-12-25 (database) correct
Excel : 25-12-2019
convert your string to a date first with
DateTime.ParseExact("25-12-1986", "dd-MM-yyyy", NULL)
then format it into your date
you can also consider TryParseExact to check for wrong format
your problem is that 05-01-2019 tends to mean 'May 1st 2019' in US style date formats, therefore you need to be very careful with formats. The policy of automatically making 25-12-1966 into 25th December (which is all it could be interpreted as) is not as helpful as it seems.

Unable to correctly parse a date from Excel cell

I'm importing Excel rows and one of the columns is a Date field. There are two scenarios in which I receive the date.
The first is I receive the date correctly as a Double. For this scenario a simple DateTime.FromOADate(parsedDouble) works.
The second scenario is for whatever reason, the client has not properly formatted the cell or the value in the cell has not been recognised correctly although is a valid date. For example the date will be 1/12/2016 which in the UK format is 1st December 2016. Excel also passes format information for the cell, so in this case it passes through the cell format "dd/mm/yyyy". This is the correct day/month/year format in excel however I need to be able to parse it in c# and I'm unable to because lower case mm is minutes and not months.
So the following won't work.
var x = DateTime.ParseExact("12/12/2016", "dd/mm/yyyy", System.Globalization.CultureInfo.InvariantCulture);
It will output 12/01/2016 00:12:00
I've had a look around and can't seem to find anyone else having the same issue and I'm not quite sure how to deal with this.
An obvious (undesirable) solution would be to hack it and map the excel format of dd/mm/yyyy to dd/MM/yyyy.

C# convert Date to text in cell in Excel (interop)

I have a pretty specific problem with the "Automatic data conversions" that Excel is doing. First I'll try to explain what exactly I'm doing and how Excel is making fun of me ;)
My program is creating a Charts for reports from temperature sensors. In the reports the first Column is the date of the reading and the second column is the reading of the sensors for that date. The problem is the automatic selection of the "XAxis series" that Excel is doing, if the first column is in DateTime format:
Here is the example for what Excel is doing with the Charts if it "smells" Date format...
And Here is how the chart looks if the first column is in Text format.
I tried some variants to convert the values in the first column but everything is too slow or messes up the values.
So far the "fastest" way that I found is:
foreach(Range cell in firstCol.Cells)
{
if (cell.Value is DateTime && !(cell.Value).ToString().Contains("\'"))
{
cell.Value = "\'" + cell.Value;
}
}
But that's not fast enough. Imagine a 100 sheets (1 sheet for each sensor) and each sheet with between 2500 and 4000 rows.
I tried things like:
usedRange.NumberFormat = "#";
as it was suggested in a couple of places on internet but that doesn't work for Date formats. It converts this:
01/12/2016 00:30 like this: 42705.02083.
So my question is if someone can suggest a better or faster way to convert the dates or to make Excel read the DateTime as text without messing up anything.
I'm sure there's a better way by fixing the X axis itself, but if all your looking for is to get the date in text format, the quick fix would be something like:
=TEXT(DATE(2016,1,12)+TIME(0,30,0),"MM/dd/yyyy hh:mm")

How to Distinguish date and other numeric formats (like number/currency) in open xml sdk SpreadSheet?

I am reading xlsx file using OpenXML SDK. There is no issue while reading shared string values but I don't know how to distinguish the actual numbers from the dates as both of them have DataType of null and they are stored as number.
Using DateTime.FromOADate() I can convert numberic value into date format but first I need to identify whether cell format is date or not, otherwise number/currency formatted cell value would also get converted into date.
I tried solution mentioned in this post
How to distinguish inline numbers from OLE Automation date numbers in OpenXML SpreadSheet?.
but it is not working for currency format,number format (negative number formatting please see attached screenshot) and some custom formats number and currency format screenshot.It would convert currency and number formats into date
I am looking for
Generic solution to distinguish date from all other numeric formats so that all the build in formats (like number,currency,Scientific) and custom formatted numeric values would not be converted into date
Is there generic way to format cell values as per formatting applied in excel sheet.Right now we are handling each formatting separately
Each cell has 2 properties r (CellReference) and s(StyleIndex)
StyleIndex for numbers is 2 and for date is 3
33938

Categories

Resources