阅读hh:mm:ss在excel文件中使用c#
我有一个Excel文件包含小时:分钟:秒(例如: 12 : 20 : 00 )
我设置格式单元格是在自定义分类中的hh:mm:ss。
我正在使用C#读取此文件中的小时:分钟:秒。
但是我收到一个string包含“12/30/1899 12:20:00”
为什么? 任何人都可以回答吗?
如何解决这个问题?
我的代码:
string con = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtFileExcelCapture.Text + ";Extended Properties='Excel 8.0;HDR=Yes;'"; using (OleDbConnection connection = new OleDbConnection(con)) { connection.Open(); OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection); using (OleDbDataReader rows = command.ExecuteReader()) { while (rows.Read()) { var nameChannel = rows[0]; string HMS = rows[1].ToString();//Result is "12/30/1899 12:20:00" } } }
谢谢
广
我可以使用下面的代码来解决我的问题
DateTime dt = DateTime.Parse(rows[1].ToString()); string HMS = String.Format("{0:HH:mm:ss}",dt);
但我不明白,
为什么在excel文件中包含的是C#中不同的string?
格式hh:mm:ss被认为是Excel中的DateTime字段,所以当你用c#读取它时,你会得到一个DateTime对象。 而且由于DateTime对象也有它的date,即使没有指定,ToString()函数也会提供完整的date和时间转换为string。 试试这个来解决你的问题:
string con = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtFileExcelCapture.Text + ";Extended Properties='Excel 8.0;HDR=Yes;'"; using (OleDbConnection connection = new OleDbConnection(con)) { connection.Open(); OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection); using (OleDbDataReader rows = command.ExecuteReader()) { while (rows.Read()) { var nameChannel = rows[0]; string HMS = (rows[1] as DateTime).TimeOfDay.ToString(); } } }
使用String.Format
格式单元格值。 当你从Excel中读取时,它包含DateTime
值,所以格式按照你的要求。
String.Format("HH:mm:ss",cellValue);
在你的情况下使用如下从单元格只获得时间部分。
rows[1].ToString("HH:mm:ss");
只需添加一个新的步骤! 如果您收到“12/30/1899 12:20:00”,则在末尾添加.Split('')[1],这将返回“12:20:00”。
尝试这个:
double d = double.Parse(workSheet.Cells[1, 1].value();); DateTime conv = DateTime.FromOADate(d);
在单元格中没有关于date的信息,所以C# 在第0天填充它
你应该做的是使用
String.Format("HH:mm:ss",cellValue);
要么
DateTime time; time.TimeOfDay.ToString("HH:mm:ss")
该值被解释为DateTime
Object。 简单地parsing它,并调用datetime.ToLongTimeString()
为什么你得到一个1899年的date是因为C#将解释值作为时间和对待它像一个DateTime
对象。 但是既然没有date归属,他就尽可能早地提前。