C#处理SQL导入Excel时间差:System.TimeSpan转换异常排查
解决C#写入Excel时间差时的类型转换异常及格式问题
问题分析
你遇到的Unable to cast object of type 'System.TimeSpan' to type 'System.IConvertible'异常,本质是Excel操作库(如EPPlus)对直接赋值TimeSpan类型的支持有限;而M列显示为空、格式为“Standard”,则是因为值的赋值逻辑与格式设置不匹配,导致Excel无法正确解析内容。
修复方案
推荐方案:按Excel原生规则存储时长
Excel将时长以数值形式存储(1天=1,1小时=1/24,以此类推),结合格式设置[h]:mm:ss可以完美展示超过24小时的时长,同时支持后续Excel内的计算操作。修改代码如下:
// Datenzeilen verarbeiten und Differenz berechnen for (int rowIndex = 2; rowIndex <= dataTable.Rows.Count + 1; rowIndex++) { object startTimeObj = dataTable.Rows[rowIndex - 2]["StartTime"]; object endTimeObj = dataTable.Rows[rowIndex - 2]["EndTime"]; if (startTimeObj != DBNull.Value && endTimeObj != DBNull.Value) { DateTime startTime = Convert.ToDateTime(startTimeObj); DateTime endTime = Convert.ToDateTime(endTimeObj); TimeSpan workingHours = endTime - startTime; // 将TimeSpan转换为Excel认可的天数数值 worksheet.Cell(rowIndex, columnCount).Value = workingHours.TotalDays; // 应用[h]:mm:ss格式,支持超过24小时的时长显示 worksheet.Cell(rowIndex, columnCount).Style.NumberFormat.Format = "[h]:mm:ss"; } else { worksheet.Cell(rowIndex, columnCount).Value = "N/A"; // 给无效值单元格设置文本格式,避免格式冲突 worksheet.Cell(rowIndex, columnCount).Style.NumberFormat.Format = "@"; } }
备选方案:纯文本展示时长
如果不需要在Excel中对时长进行计算,仅需展示,可以直接写入格式化后的字符串,但需先将单元格设置为文本格式:
// Datenzeilen verarbeiten und Differenz berechnen for (int rowIndex = 2; rowIndex <= dataTable.Rows.Count + 1; rowIndex++) { object startTimeObj = dataTable.Rows[rowIndex - 2]["StartTime"]; object endTimeObj = dataTable.Rows[rowIndex - 2]["EndTime"]; if (startTimeObj != DBNull.Value && endTimeObj != DBNull.Value) { DateTime startTime = Convert.ToDateTime(startTimeObj); DateTime endTime = Convert.ToDateTime(endTimeObj); TimeSpan workingHours = endTime - startTime; // 先设置单元格为文本格式 worksheet.Cell(rowIndex, columnCount).Style.NumberFormat.Format = "@"; // 写入格式化后的时长字符串 worksheet.Cell(rowIndex, columnCount).Value = workingHours.ToString(@"[h]:mm:ss"); } else { worksheet.Cell(rowIndex, columnCount).Value = "N/A"; worksheet.Cell(rowIndex, columnCount).Style.NumberFormat.Format = "@"; } }
额外检查项
- 确认
columnCount变量的值对应Excel的M列(M是第13列,需保证columnCount = 13,如果是动态计算列数,要验证逻辑正确性)。 - 若使用EPPlus 5及以上版本,需确保已正确配置商业许可证(非商业场景可使用免费许可证),避免其他异常。
内容的提问来源于stack exchange,提问作者k.sere
相关产品推荐
相关产品推荐

