将datagrid导出到excel时出现日期问题

时间:2014-11-09 22:51:01

标签: excel datagrid

我有以下代码以excel格式导出我的datagrid的内容。它可以工作,但问题是显示日期的列而不是显示“########”的日期。我必须手动格式化列才能正确显示日期。有没有办法在报告时自动执行此操作? 提前谢谢。

Public Sub export_auto_oraria()
    Dim ExcelApp As Object, ExcelBook As Object
    Dim ExcelSheet As Object
    Dim i As Integer
    Dim j As Integer

    'create object of excel
    ExcelApp = CreateObject("Excel.Application")
    ExcelBook = ExcelApp.WorkBooks.Add
    ExcelSheet = ExcelBook.WorkSheets(1)

    With ExcelSheet
        For i = 1 To Me.DataGridView3.RowCount
            .cells(i, 1) = Me.DataGridView3.Rows(i - 1).Cells("d_id").Value
            For j = 1 To DataGridView3.Columns.Count - 1
                .cells(i, j + 1) = DataGridView3.Rows(i - 1).Cells(j).Value
            Next
        Next
    End With

    ExcelApp.Visible = False

    ExcelSheet = Nothing



    Dim path As String = "C:\Users\book1.xlsx"
        ExcelBook.SaveAs(path)
        ExcelApp.Workbooks.Close()
        ExcelApp.Quit()

end sub   '? is this where it ends

1 个答案:

答案 0 :(得分:0)

这种对数据传输的补充应该会有所帮助。

With ExcelSheet
    For i = 1 To Me.DataGridView3.RowCount
        .cells(i, 1) = Me.DataGridView3.Rows(i - 1).Cells("d_id").Value
        For j = 1 To DataGridView3.Columns.Count - 1
            .cells(i, j + 1) = DataGridView3.Rows(i - 1).Cells(j).Value
        Next
    Next
    For j = 1 To DataGridView3.Columns.Count
        .columns(j).EntireColumn.AutoFit
    Next
End With