【发布时间】:2022-11-30 08:28:36
【问题描述】:
我需要从 excel 文件中提取时间。 excel 中的时间以小时:分钟:秒表示。我拥有的读取时间的 c# 代码是:
DateTime dt = DateTime.Parse(worksheet.Cells[row, 3].Value.ToString());
string GetTime = String.Format("{0:t}", dt);
此代码适用于一个文件,但当我插入另一个类似文件时,它不会读取时间。有谁知道为什么会这样。
读取时间的 Excel 表格:
| Id | Date | Time |
|---|---|---|
| 1 | 18/11/2022 | 11:51:00 |
不读取时间的 Excel 表格:
| Id | Date | Time |
|---|---|---|
| 1 | 08/08/2022 | 06:54:00 |
【问题讨论】:
-
不要使用
Cells[row, 3].Value.ToString())开头。 Excel 支持日期,任何 Excel 库都应将日期值读取为 DateTime。如果该值为 DateTime,则只是在浪费 RAM。将值转换为 DateTime 并使用 TimeOfDay 属性读取时间。例如`((DateTime)worksheet.Cells[row, 3].Value).TimeOfDay -
不看时间怎么办?抛出异常?
-
在输出窗口中,我读到“抛出的异常:'System.InvalidCastException'”
标签: c#