C# 正在从excel文件读取值,获取不正确的值
我正在读取excel文件,其中包含列名time,该列名由时间组成,例如14:10:25,对于某些文件,我的代码工作正常,但对于大多数文件,当我读取列时,它返回这些随机浮点值0.402778C# 正在从excel文件读取值,获取不正确的值,c#,.net,excel,C#,.net,Excel,我正在读取excel文件,其中包含列名time,该列名由时间组成,例如14:10:25,对于某些文件,我的代码工作正常,但对于大多数文件,当我读取列时,它返回这些随机浮点值0.402778 Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook xlWorkbook = x
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();
您需要检查输入字符串是否为数字格式。然后将输入转换为数字格式的特定时间 在这里,我创建了一个控制台应用程序,供您演示
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);
}
}
输出:
单元格包含格式化的值或字符串?字符串,而不是格式化的值。时间将存储为数字。例如,14:10:25为0.59056712962963这可能存储为需要转换为数字/时间的文本。时间计算为[午夜后的秒数/白天的秒数],因此14h10mn25s=14*3600秒+10*60秒+25秒/3600*24