从vb.net DGV导出到Excel

时间:2018-03-13 10:45:08

标签: excel vb.net date datetime types

我正在尝试将 DGV 显示数据导出到Excel,并且可以使用以下代码正常工作。问题是日期日期时间列在导出到Excel后会得到一些随机数。此外,我必须更改列并选择和数据类型为short日期以显示日期。

以下代码包含来自 SQL DGV 数据。我希望单元格范围C:C中的日期列为excel中的日期。

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    picLoading_TO.Visible = True
    picLoading_TO.BringToFront()

    Try
        Dim excel As Microsoft.Office.Interop.Excel.Application = Nothing
        Dim workbook As Microsoft.Office.Interop.Excel.Workbook = Nothing
        Dim sheet1 As Microsoft.Office.Interop.Excel.Worksheet = Nothing


        excel = New Microsoft.Office.Interop.Excel.Application()
        'excel.Visible = True
        workbook = excel.Workbooks.Add(System.Reflection.Missing.Value)
        sheet1 = DirectCast(workbook.Sheets(1), Microsoft.Office.Interop.Excel.Worksheet)

        Dim StartCol As Integer = 1
        Dim StartRow As Integer = 1
        Dim j As Integer = 0, i As Integer = 0
        Dim visibleCols As Integer = 0

        Dim sOutput As String = ""
        ' Dim sDelimiter As String = txtDelimiter.Text


        'Write Headers
        For j = 0 To dgvOrders.Columns.Count - 1
            If dgvOrders.Columns(j).Visible Then

                Dim myRange As Microsoft.Office.Interop.Excel.Range = DirectCast(sheet1.Cells(StartRow, StartCol + visibleCols), Microsoft.Office.Interop.Excel.Range)
                myRange.Value2 = dgvOrders.Columns(j).HeaderText
                visibleCols += 1
            End If
        Next

        StartRow += 1


        'Write datagridview content
        For i = 0 To dgvOrders.Rows.Count - 1
            visibleCols = 0

            For j = 0 To dgvOrders.Columns.Count - 1
                If dgvOrders.Columns(j).Visible Then

                    Dim myRange As Microsoft.Office.Interop.Excel.Range = DirectCast(sheet1.Cells(StartRow + i, StartCol + visibleCols), Microsoft.Office.Interop.Excel.Range)
                    myRange.Value2 = If(dgvOrders(j, i).Value Is Nothing, "", dgvOrders(j, i).Value)
                    visibleCols += 1

                End If

            Next

        Next

        picLoading_TO.Visible = False
        picLoading_TO.SendToBack()
        excel.Visible = True

    Catch ex As Exception
        MsgBox(ex.ToString())
    End Try
End Sub

0 个答案:

没有答案