从Excel单元捕获时间值

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

这是我的代码…

 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 =我的date时间select器,它可以帮助我决定打开哪个文件
  • i =是一个整数,帮助我决定该单元格的行号
  • range =是从Microsoft.Office.Interop.Excel.Range创build的对象

在我的示例中,当i = 11F11是包含时间值06:30的单元格(在Excel中, fx : 06:30:00 06:30 fx : 06:30:00 06:30 fx : 06:30:00 )。 但是,当我尝试获得该值时,将返回0.263888888888889double 0.263888888888889

我怎样才能得到正确的格式,因为它显示在Excel中,而不是一个毫无意义的双重价值?

Excel在内部将时间存储为包含24小时小数小数的双精度:所以上午6:30将是0.2708333

处理Exceldate时,date可以存储为date的string表示forms,也可以是OAdate (OLE自动化date)。 我发现,检查这两种types是parsingExceldate时最安全的路线。

以下是我为转换而写的扩展方法:

 /// <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; 

Excel将时间存储在一天中的几分之一,因为12/24 = 1/2 = 0.5,所以12:00将被存储为0.5

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

要获得会议logging(因为每天有1440分钟),你必须将该值乘以1440,这会给你从00:00开始的会议logging,你需要除以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 }