在Excel文件上写入TimeSpan

我正在做一个vb.net程序,我在Excel文件上写了一些数据。 这到目前为止不是问题! 但是,在文件上写TimeSpans时遇到了麻烦。

例如,在代码上:

Sub DataExport() 'Create a bridge between Console and Excel: Dim ExcelBridge As Excel.Application ExcelBridge = New Excel.Application Dim NewWorkbook As Excel.Workbook = ExcelBridge.Workbooks.Open("P:\HelpDesk\Definitions\Models\RPMAN.xlsm") NewWorkbook.Application.DisplayAlerts = False 'Create Desktop folders if they don't exist: If Dir(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\Reports", vbDirectory) = "" Then MkDir(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\Reports") End If If Dir(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\Reports\HelpDesk", vbDirectory) = "" Then MkDir(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\Reports\HelpDesk") End If 'Test variables: Dim test01 As Integer = 2 Dim test02 As String = "FieldA" Dim test03 As String = "FieldB" Dim test04 As String = "FieldC" Dim test05 As Date = DateSerial(2017, 1, 1) Dim test06 As Date = Now() Dim test07 As TimeSpan = TimeSpan.Parse("1.12:03:55") Dim test08 As String = "FieldD" Dim test09 As TimeSpan = TimeSpan.Parse("3.20:43:07") Dim test10 As String = "FieldE" 'Write Excel file: With NewWorkbook.Sheets("RESUMO") .cells(3, 1).formular1c1 = test01 .cells(3, 2).formular1c1 = test02 .cells(3, 3).formular1c1 = test03 .cells(3, 4).formular1c1 = test04 .cells(3, 5).formular1c1 = test05 .cells(3, 6).formular1c1 = test06 .cells(3, 7).formular1c1 = test07 .cells(3, 8).formular1c1 = test08 .cells(3, 9).formular1c1 = test09 .cells(3, 10).formular1c1 = test10 End With 'Save Excel file: NewWorkbook.SaveAs(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\Relatórios\HelpDesk\ITreport" & Format(Now(), "yyyyMMddHHmmss") & ".xlsm") 'Close Excel file NewWorkbook.Close() End Sub 

我得到一个错误的线

 .cells(3, 7).formular1c1 = test07 

它根本不让我写它。

随着On Error Resume Next ,代码写入所有其他但TimeSpans。

可能这个问题有一个简单的解决scheme,但我真的没有看到它。 任何帮助将非常感激。 而且,一如既往,先谢谢大家。

System.TimeSpan没有直接对应的Exceltypes。 您将需要将其值转换为Excel可以理解的东西。 Excel将date时间值存储为基准date的偏移量,表示从所述偏移量开始的全天和小数天的总数。

但是,TimeSpan结构具有TotalDays Exceldate时间值的TotalDays属性。 Excel单元格应该有一个NumberFormat设置为正确显示值(“d:HH:mm:ss”)。

 NewWorkbook.Sheets("RESUMO").Cells(3, 7).Value2 = test07.TotalDays NewWorkbook.Sheets("RESUMO").Cells(3, 7).NumberFormat = "d:HH:mm:ss"