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 = 11は(Excel では) でF11ある時間値を含むセルです。ただし、その値を取得しようとすると、次のような型が返されます06:30fx : 06:30:00double0.263888888888889

無意味な double 値ではなく、Excel で表示されるように正しくフォーマットされた値を取得するにはどうすればよいですか?

4

3 に答える 3

5

Excel は、24 時間制の小数部を含む double として内部的に時間を格納します。したがって、午前 6 時 30 分は 0.2708333 になります。

于 2011-03-13T17:13:24.743 に答える
5

Excel の日付を処理する場合、日付は日付の文字列表現として格納するか、OA 日付(OLE Automation Date) のいずれかにすることができます。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;
于 2011-03-13T17:30:01.297 に答える
2

Excel は時間を 1 日の分数で保存します。12/24 = 1/2 = 0.5 であるため、12:00 は 0.5 として保存されます。

時間を取得するには、Excel の時間を 24 倍し、結果を整数に丸める必要があります。

分を取得するには (1 日は 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 に答える