在Excel文件上写一个TimeSpan

时间:2017-05-10 15:09:53

标签: excel vb.net time

我制作了一个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之外的所有其他内容。

可能这个问题有一个简单的解决方案,但我真的没有看到它。 任何帮助将非常感激。并且,一如既往地提前感谢你们。

1 个答案:

答案 0 :(得分:1)

System.TimeSpan没有直接对应的Excel类型。您需要将其值转换为Excel可以理解的值。 Excel将日期时间值作为基准日期的偏移量存储为Double,表示从所述偏移量开始的整天和小数天的总数。

但是,TimeSpan结构具有TotalDays属性,该属性将用作Excel日期时间值。 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"