从Excel文件读取值,获取不正确的值

时间:2018-10-04 06:42:44

标签: c# .net excel

我正在读取包含列名 time 的excel文件,其中包含时间,例如14:10:25,对于某些文件,我的代码可以正常工作,但对于大多数文件,当我读取时该列,则返回这些随机浮动值“ 0.402777777777778”

Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(excel_file_path.Text);
Microsoft.Office.Interop.Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Microsoft.Office.Interop.Excel.Range xlRange = xlWorksheet.UsedRange;
string Time = xlRange.Cells[2, 1].Value2.ToString();

1 个答案:

答案 0 :(得分:1)

您需要检查输入字符串是否为数字格式。然后以数字格式将您的输入转换为特定时间。

在这里,我创建一个控制台应用程序用于演示。

class Program
{
    static void Main(string[] args)
    {
        string input1 = "0.402777777777778";
        double outVal = 0;

        if (double.TryParse(input1, out outVal))
        {
            var t = DoubleToTimeSpan(outVal);
            Console.WriteLine("Input: " + input1);
            Console.WriteLine("Output: " + t);
        }
        else
        {
            //Your string is in time format
        }

        Console.WriteLine();

        string input2 = "0.59056712962963";

        if (double.TryParse(input2, out outVal))
        {
            var t = DoubleToTimeSpan(outVal);
            Console.WriteLine("Input: " + input2);
            Console.WriteLine("Output: " + t);
        }
        else
        {
            //Your string is in time format
        }


        Console.ReadLine();
    }


    public static TimeSpan DoubleToTimeSpan(double dValue)
    {
        int seconds_in_a_day = 86400;
        int iDays = (int)dValue;
        double dSeconds = Math.Floor(seconds_in_a_day * (dValue -
        iDays));
        return new TimeSpan(iDays, 0, 0, (int)dSeconds, 0);
    }
}

输出:

enter image description here