问题描述
我正在使用包从.xlsx文件读取。我需要从单元格读取TimeSpan对象。
excel单元格将包含 hh:mm格式的数据,例如: 09:00或 18:30,不带引号。
I am using EPPlus package to read from an .xlsx file. I need to read a TimeSpan object from a cell.The excel cell would contain a data in "hh:mm" format, for example: "09:00" or "18:30" without the quotation marks.
这是我的代码:
string myString = workSheet.Cells[1,1].Value.ToString();
double d = double.Parse(myString);
DateTime dt = DateTime.FromOADate(d);
TimeSpan ts = new TimeSpan(dt.Hour, dt.Minute, dt.Second);
在Excel文件myString中的 09:00或 08:30数据包含 0.375或 0.354166666666667,并且ts可以按预期计算。
但是对于excel文件中的 10:00,myString包含
30/12/1899 10:00:00 AM,并且double值的解析失败,因此无法计算ts。
for "09:00" or "08:30" data in excel file myString contains "0.375", or "0.354166666666667" respectively and ts can be calculated as expected.But for "10:00" in excel file myString contains"30/12/1899 10:00:00 AM" and the parsing of the double value fails hence ts cannot be calculated.
我不确定为什么这种情况不一致。我如何从Excel单元格(更确切地说是具有通用格式的单元格)中一致地读取双精度值?请帮忙。
I am not sure why this is happening inconsistently . How can I consistently read a double value from an excel cell (more precisely a cell with a General format)? Please help.
这是我的简化代码(在Siddharth Rout的建议之后):
Here is my simplified code (After the suggestion from Siddharth Rout):
string myString = workSheet.Cells[1,1].Text.ToString();
TimeSpan ts = TimeSpan.Parse(myString);
到目前为止,它可以使用各种值。
So far it is working with various values.
推荐答案
这是我的简化代码(在Siddharth Rout的建议之后):
Here is my simplified code (After the suggestion from Siddharth Rout):
string myString = String.Format("{0}", workSheet.Cells[1,1].Text);
TimeSpan ts = TimeSpan.Parse(myString);
到目前为止,它可以处理各种值。
So far it is working with various values.
这篇关于从Excel单元格读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!