从Excel单元格捕获时间值

msh*_*rpp 2 c# excel cell-formatting

我正在编写一个Excel应用程序,它将从Excel文件读取和写入指定的值,并将它们显示给用户.但是,当我尝试从具有Number Format类型或函数类型的单元格中读取时,我'hh:min' (Hour:Min)无法获得该值,我究竟想要什么.

这是我的代码......

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);
Run Code Online (Sandbox Code Playgroud)

哪里...

  • ws =我的工作表
  • dateTimePicker1 =我的日期时间选择器,它可以帮助我决定打开哪个文件
  • i =是一个整数,帮助我决定该单元格的行号
  • range =是从Microsoft.Office.Interop.Excel.Range创建的对象

在我的示例中,何时i = 11,F11是包含时间值的单元格06:30(在Excel中fx : 06:30:00).但是,当我尝试获取该值时,它返回一个double类型,如0.263888888888889

如何在Excel中显示格式正确的值,而不是无意义的双值?

Cha*_*ams 5

Excel将内部时间存储为包含24小时日的小数部分的双精度数:因此上午6:30将为0.2708333


Met*_*urf 5

处理 Excel 日期时,日期可以存储为日期的字符串表示形式,也可以是OA 日期(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;
}
Run Code Online (Sandbox Code Playgroud)

在您的示例中,用法是:

TimeSpan time = f11Value.ParseExcelDate().TimeOfDay;
Run Code Online (Sandbox Code Playgroud)