2011-03-13 87 views
2

我正在写一个Excel应用程序,它将读取和写入Excel文件中的指定值,并将它们显示给用户。但是,当我尝试从具有Number Format或输入函数'hh:min' (Hour:Min)的单元格读取数据时,我无法获得该值,具体如何。从Excel单元捕获时间值

这里是我的代码...

ws[dateTimePicker1.Value.Day + 1].get_Range("F" + i.ToString(), Type.Missing); 
    if (range.Value2 != null) 
     val += " - " + range.Value2.ToString(); //Sets FXX to val 
    lbHK1.Items.Add(val); 

哪里..​​.

  • ws =我的工作表
  • dateTimePicker1 =我的日期时间选择器,这有助于我决定哪些文件会被打开
  • i =是一个整数,帮助我决定该单元格的行号
  • range =距离Microsoft.Office.Interop.Excel.Range

在我的例子,在创建对象时i = 11F11是包含时间值,它是06:30小区(在Excel,fx : 06:30:00)。但是,当我尝试获得该值时,它会返回double类型,如0.263888888888889

如何获取正确格式的值,因为它在Excel中显示,而不是无意义的double值?

回答

5

Excel存储在内部倍加倍含有一天24小时的小数:所以6:30 AM将0.2708333

+0

因为当我通过的GetType()方法得到的值类型很有意思,它说这是一个双值类型。无论哪种方式,那么我该如何解决这个问题呢?你能在这里输入一个简单的代码吗? – msharpp 2011-03-13 17:22:15

3

当用Excel日期处理,日期可以被存储为一个字符串表示日期,或者它可能是一个OA date(OLE自动化日期)。我发现检查这两种类型是解析Excel日期时最安全的路线。

下面是一个扩展方法我写的转换:

/// <summary> 
/// Sometimes the date from Excel is a string, other times it is an OA Date: 
/// Excel stores date values as a Double representing the number of days from January 1, 1900. 
/// Need to use the FromOADate method which takes a Double and converts to a Date. 
/// OA = OLE Automation compatible. 
/// </summary> 
/// <param name="date">a string to parse into a date</param> 
/// <returns>a DateTime value; if the string could not be parsed, returns DateTime.MinValue</returns> 
public static DateTime ParseExcelDate(this string date) 
{ 
    DateTime dt; 
    if(DateTime.TryParse(date, out dt)) 
    { 
     return dt; 
    } 

    double oaDate; 
    if(double.TryParse(date, out oaDate)) 
    { 
     return DateTime.FromOADate(oaDate); 
    } 

    return DateTime.MinValue; 
} 

在您的例子中,用法是:

TimeSpan time = f11Value.ParseExcelDate().TimeOfDay; 
2

Excel存储时间,每天12:00会的分数保存为0.5因为12/24 = 1/2 = 0.5

要获得小时数,必须将excel时间乘以24,然后将结果四舍五入为整数。

要获得会议记录(因为每天有1440分钟),您必须将该值乘以1440,这会给出从00:00开始经过的会议记录,您需要除以60,然后处理剩余的会议记录的操作来获得分钟的时间。

这里有一个片段:

string parseExcelHour(string cellInput){ 

    double excelHour = 0; 

    try{ 
     excelHour = Double.Parse(cellInput); 
    }catch { } 

    int hour = (int) (excelHour * 24);// with the int cast you get only an integer. 
    int min = (int) (excelHour * 1440 % 60); //mod (%) takes only the remainder and then the cast to int will round the number 

    return (hour < 10? "0":"") + hour + ":" + (min < 10? "0":"") + min; //will print HH:mm 
} 
+0

努力工作,并在某些情况下工作。不幸的是,它不能正确解析所有的时间。我有17:05回来作为17:4 – Shumii 2016-05-07 06:46:47

+0

@Shumii由于浮动和双重操作不准确,你可能会失去一些数据,并得到29。999999分钟,而不是30。 – Cheloide 2017-09-26 14:46:41