简体   繁体   中英

Finding dates for manipulation in an Excel Range with C#

I have a situation where I am working with an Excel workbook and I would like to find each cell that has a date in it to do some work on that cell specifically. The dates are in columns, but from what I have read, it seems to be easier just to grab the entire used range and check the cells. Unfortunately, what I am finding is that once I have the cells, I cannot detect a date within them. Here is the contents of the method I am using:

Excel.Worksheet sheet = (Excel.Worksheet)oWB.ActiveSheet;
Excel.Range range = sheet.UsedRange;
//get an array of values from the cells
System.Array cellvals = (System.Array)range.Cells.Value2;
//go through each 
foreach(object obj in cellvals)
{
    //is it a datetime?
    DateTime testdt = new DateTime();
    double holder = 0.00;
    if (double.TryParse(obj.ToString(),out holder)) 
    {
        bool test = DateTime.TryParse(holder.ToString(), out testdt);
        if (test)
        {
            //check it against litmus test
            Console.WriteLine("Hit");
        }
     }
}

Even though I have a column of dates in my test data, the if(test) conditional is never entered. Here is an example of one of the strings in the date column:

01/08/2007 14:50:50.42

Most of what I have found online has been about finding very specific date strings, and not just dates in general. I was hoping someone might be able to help me find why I am not hitting that conditional as expected.

Using the approach you've taken above, you cannot differentiate between a cell that contains a double and one that contains a true date/time. Also, you can't parse the string representation of a Double as a DateTime. There are ways to convert from an OLE DATE (which is just a double) to a .NET DateTime, but you may not need to do that.

Have you seen this note on the documentation of the Value2 property?

The only difference between this property and the Value property is that the Value2 property doesn't use the Currency and Date data types. You can return values formatted with these data types as floating-point numbers by using the Double data type.

Use the Value property instead, and I believe you'll get .NET DateTimes where you expect them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM