3

我正在编写一个 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);

在哪里...

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

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

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

4

3 回答 3

5

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

于 2011-03-13T17:13:24.743 回答
5

When dealing with Excel dates, the date can either be stored as a string representation of a date, or it may be an OA date (OLE Automation Date). I've found that checking for both types is the safest route when parsing Excel dates.

Here's an extension method I wrote for the conversion:

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

In your example, the usage would be:

TimeSpan time = f11Value.ParseExcelDate().TimeOfDay;
于 2011-03-13T17:30:01.297 回答
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
}
于 2015-01-30T14:08:24.587 回答