Reading Datetime value From Excel sheet - c#

when am trying to read datetime type value from excel sheet it is returning a double value.for example if want to read value '2007-02-19 14:11:45.730' like this, i am getting a double type value .further i am converting this double value using timespan,but not complete successfully because i am getting only this value '2007-02-19 12:00:00 AM'
now i want exact same datetime value as first one. My code is like :-
TimeSpan datefromexcel = new TimeSpan(Convert.ToInt32((range.Cells[rCnt, cCnt] as Excel.Range).Value2), 0, 0, 0);
DateTime inputdate = new DateTime(1900, 1, 1).Add(datefromexcel);
arrrow2[cCnt - 1] = inputdate.ToString();
Please help!!!
Thanks.

You need to convert the date format from OLE Automation to the .net format by using DateTime.FromOADate.
double d = double.Parse(b);
DateTime conv = DateTime.FromOADate(d);

Perhaps you could try using the DateTime.FromOADate method to convert between Excel and .net.

Reading Datetime value From Excel sheet : Try this will be work.
string sDate = (xlRange.Cells[4, 3] as Excel.Range).Value2.ToString();
double date = double.Parse(sDate);
var dateTime = DateTime.FromOADate(date).ToString("MMMM dd, yyyy");

Alternatively, if your cell is already a real date, just use .Value instead of .Value2:
excelApp.Range[namedRange].Value
{21/02/2013 00:00:00}
Date: {21/02/2013 00:00:00}
Day: 21
DayOfWeek: Thursday
DayOfYear: 52
Hour: 0
Kind: Unspecified
Millisecond: 0
Minute: 0
Month: 2
Second: 0
Ticks: 634970016000000000
TimeOfDay: {00:00:00}
Year: 2013
excelApp.Range[namedRange].Value2
41326.0

Or you can simply use OleDbDataAdapter to get data from Excel

i had a similar situation and i used the below code for getting this worked..
Aspose.Cells.LoadOptions loadOptions = new Aspose.Cells.LoadOptions(Aspose.Cells.LoadFormat.CSV);
Workbook workbook = new Workbook(fstream, loadOptions);
Worksheet worksheet = workbook.Worksheets[0];
dt = worksheet.Cells.ExportDataTable(0, 0, worksheet.Cells.MaxDisplayRange.RowCount, worksheet.Cells.MaxDisplayRange.ColumnCount, true);
DataTable dtCloned = dt.Clone();
ArrayList myAL = new ArrayList();
foreach (DataColumn column in dtCloned.Columns)
{
if (column.DataType == Type.GetType("System.DateTime"))
{
column.DataType = typeof(String);
myAL.Add(column.ColumnName);
}
}
foreach (DataRow row in dt.Rows)
{
dtCloned.ImportRow(row);
}
foreach (string colName in myAL)
{
dtCloned.Columns[colName].Convert(val => DateTime.Parse(Convert.ToString(val)).ToString("MMMM dd, yyyy"));
}
/*******************************/
public static class MyExtension
{
public static void Convert<T>(this DataColumn column, Func<object, T> conversion)
{
foreach (DataRow row in column.Table.Rows)
{
row[column] = conversion(row[column]);
}
}
}
Hope this helps some1
thx_joxin

You may want to try out simple function I posted on another thread related to reading date value from excel sheet.
It simply takes text from the cell as input and gives DateTime as output.
I would be happy to see improvement in my sample code provided for benefit of the .Net development community.
Here is the link for the thread C# not reading excel date from spreadsheet

Another option: when cell type is unknown at compile time and cell is formatted as Date Range.Value returns a desired DateTime object.
public static DateTime? GetAsDateTimeOrDefault(Range cell)
{
object cellValue = cell.Value;
if (cellValue is DateTime result)
{
return result;
}
return null;
}

Related

C# DateTime from Excel turns into float number

I have an excel file in the first column which contains dates in the format dd.MM.yyyy hh:mm:ss. I'm trying to display data from an excel table in datagridview, but the date is displayed as a float number.
I tried to convert the date to the desired format in this way, but it does not work:
worksheet.Cells[2, 1, endCell.Row, 1].Style.Numberformat.Format = "dd.MM.yyyy hh:mm:ss";
The full code of my method:
public static DataTable readTableFromExcel(FileInfo file)
{
DataTable table = new DataTable();
Console.WriteLine(file.Exists);
using (ExcelPackage package= new ExcelPackage(file))
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
ExcelCellAddress startCell = worksheet.Dimension.Start;
ExcelCellAddress endCell = worksheet.Dimension.End;
ExcelRange range = worksheet.Cells[startCell.Row, startCell.Column, endCell.Row, endCell.Column];
ExcelTable excelTable = worksheet.Tables.Add(range, "table");
Console.WriteLine(worksheet.Cells[2, 1].Value.ToString());
table = excelTable.ToDataTable();
}
return table;
}
String with Console.Writeline outputs 44912,0912268519 instead of 17.12.2022 2:11:22.
Then I output the data to datagridview: tableView.DataSource = table;
And it looks like: https://i.stack.imgur.com/aXx6V.png
File used: https://drive.google.com/drive/folders/1hXKmKs_F7EyO5GdVU3HVATxDLlFWO4jk?usp=share_link
How can I display the datetime correctly?
In Excel, dates and times are stored as a floating point number representing the number of days since the epoch date of January 1, 1970. This means that when you read a date or time value from an Excel file into a C# DateTime object, you will need to convert the floating point value to a DateTime object.
// Assume that the Excel date value is stored in a variable called "excelDate"
// Convert the Excel date value to a DateTime object
DateTime dateTime = DateTime.FromOADate(excelDate);
system.datetime.fromoadate

Input string was not in a correct format while reading date from excel

I am trying to upload an excel sheet. Now I am getting an error for the date column. I was able to fix it up to this point base on some suggestions here. This is the date format on the excel 20/4/2020
But I couldn't figure it out from this point. I kept getting. I was able to get the Value from the excel sheet and stored in string date
Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status,
TypeCode type) at System.Double.Parse(String s)
Here is my code below
//be on the first column [r,c]
int row = 2;
for (int i = 2; i <= noOfRow; i++) //start from the second row
{
if (!string.IsNullOrEmpty(workSheet.Cells[i, 3].Text))
{
string date = workSheet.Cells[i, 3].Value.ToString();
try
{
double d = double.Parse(date);//Error is coming from here
DateTime conv = DateTime.FromOADate(d);
}
catch (Exception ex)
{}
}
}
I will appreciate if someone can help me out
Thanks
The problem occurs because value in the variable date = "11/5/2020" is not a double value. It is a DateTime value. To fix you problem you should use the next code to convert value in the date variable into DateTime value:
DateTime d = DateTime.ParseExact(date, "d/M/yyyy", CultureInfo.InvariantCulture);
Method DateTime.ParseExact allows you to set the format of the parsed date.
The above code worked for me the day you shared with me. But now I am
getting this error {"String '6/3/2020 12:00:00 AM' was not recognized
as a valid DateTime."} I have tried implementing almost everything on
stackoverflow.
If date string in your excel file can be in different formats, then you can use overload of the method DateTime.ParseExact that supports specifying several parse formats. For example:
string[] formats = {"d/M/yyyy", "d/M/yyyy hh:mm:ss tt"};
DateTime d = DateTime.ParseExact(date, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
Here is complete sample that demostrates this overload of the method DateTime.ParseExact.

Convert DateTime in DataRow to a formatted date string

I'm hoping that there is something I am not seeing clearly, but to simplify, I have the below code
foreach (DataRow row in dt.Rows)
{
row["StartOn"] = Convert.ToDateTime(row["StartOn"].ToString()).ToString("MMM dd").ToString();
}
If I run the below code I get “Aug 09”
Convert.ToDateTime(row["StartOn"].ToString()).ToString("MMM dd").ToString();
If I look to see what is in row[“StartOn”] after this change it contains “8/9/2016 12:00:00 AM”
I'm unable to format my DataRow to an "MMM dd" format
StartOn is apparently a DateTime type. DateTime types do NOT have a format. They are an object that specifies year, month, date, and time (among other things). All you are doing in your conversions is stripping out the time so that the new datetime has a time of 12:00 am.
What is dt.Columns["StartOn"]. I suspect this is DateTime. Let me break down your single line of code into 2 lines.
string s = Convert.ToDateTime(row["StartOn"].ToString()).ToString("MMM dd").ToString();
row["StartOn"] = s;
In line 1, you are converting a DateTime object to a string object. But on line 2, you are implicitly converting your string to a DateTime
var dt = new DataTable();
dt.Columns.Add("StartOn", typeof(DateTime));
dt.Rows.Add(DateTime.Today);
foreach (DataRow row in dt.Rows) {
var data = Convert.ToDateTime(row["StartOn"].ToString()).ToString("MMM dd").ToString();
Console.WriteLine($"Type of stored data is: {data.GetType()}");
row["StartOn"] = data;
}
// fetch the data
var fetchedData = dt.Rows[0][0];
Console.WriteLine($"Type of Fetched Data is: {fetchedData.GetType()}");
BTW, you can use the below line to do the conversion
((DateTime)row["StartOn"]).ToString("MMM dd");

Conversion of date string and time string into datetime in c#

we have a Data-table with 3 fields Date(string type)(MM/dd/YYYY) Hours(string type)(24 hours format) and minutes(string Type) i need to create a another column that of date time based from the above 3 columns and need to sort the data table by that date time column
Date Hours Minutes
5/19/2015 12 30
11/18/2015 23 45
I tried to create a string like this Date +" "+Hours+":"+ Minutes and converted to datetime. But I am getting an error
"String was not recognized as a valid DateTime."
can any help me in this issue please
Why do you store everything as string in the first place? However, you can build the complete DateTime by using DateTime.TryParseExact. Then you can use Linq-To-DataTable for the ordering. Finally create the ordered table with CopyToDataTable:
table.Columns.Add("DateColumn", typeof(DateTime));
foreach (DataRow row in table.Rows)
{
string dateTimeString = String.Format("{0} {1}:{2}",
row.Field<string>("Date"),
row.Field<string>("Hours"),
row.Field<string>("Minutes"));
DateTime date;
if(DateTime.TryParseExact(dateTimeString, "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out date));
{
row.SetField("DateColumn", date);
}
}
table = table.AsEnumerable()
.OrderBy(row => row.Field<DateTime>("DateColumn"))
.CopyToDataTable();
So you don't need to store the hours and minutes separately, a DateTime stores all informations in one object. Three of your columns in the table are redundant.
You need to iterate your DataTable and use DateTime.ParseExact with explicit format string, like that:
DataTable dt;
foreach (var row in dt.Rows)
row["DateTime"]=DateTime.ParseExact(row.Date +" "+row.Hours+":"+ row.Minutes,"MM/dd/yyyy HH:mm",null)
Use ParseExact method. I found it very simple
table.Columns.Add("MixedData",typeof(DateTime));
foreach (DataRow row in table.Rows)
{
DateTime date = DateTime.ParseExact(row["Dates"].ToString() + " " + row["Hours"] + ":" + row["Minutes"], "M/dd/yyyy H:mm", CultureInfo.InvariantCulture);
row["MixedData"] = date;
table.AcceptChanges();
}

Creating and comparing dates from current week to a cell.innertext string value

I need to compare a cell's value to dates in the scope of the current week.
I need to see if a date from a cell can be matched to any date in the current week. If so, success Match should be incremented.
I was thinking about putting dates in an array or dictionary and then compare it to a cell value.
DateTime cellValue = DateTime.Now;
var beginweek = DateTime.Now.Date.AddDays( (int)DateTime.Now.DayOfWeek *-1);
var endweek = beginweek.AddDays(6);
if (cellValue.Date >= beginweek.Date && cellValue.Date <= endweek.Date)
{
//do something
}
You can use the Week class of the Time Period Library for .NET:
// ----------------------------------------------------------------------
public bool IsInCurrentWeek( DateTime test )
{
return new Week().HasInside( test );
} // IsInCurrentWeek
I fixed this with a solution based on Jeremy's answer. The difference is that I used
DateTime cellDateValue = Convert.ToDateTime(((HtmlCell)cell).InnerText);
instead of
DateTime cellValue = DateTime.Now;

Categories

Resources