Public Class frmShowDataDouble

    Private Sub DataGridView1_DataSourceChanged(sender As Object, e As EventArgs)
        dgv1.AutoSize = True
        dgv1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
    End Sub

    Private Sub DataGridView2_DataSourceChanged(sender As Object, e As EventArgs)
        dgv2.AutoSize = True
        dgv2.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
    End Sub


    Public Sub genCSV_startWithExcel(dgv As DataGridView)
        Dim sPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Personal) & "\VERAG\Monitoring\tmp\" ' My.Computer.FileSystem.GetTempFileName
        If Not My.Computer.FileSystem.DirectoryExists(sPath) Then
            My.Computer.FileSystem.CreateDirectory(sPath)
        End If
        Dim fn As String = sPath & "tmp_" & Now.ToString("ddMMyyyyHHmmss") & ".csv"
        Dim outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(fn, False)
        Dim clmns As String = ""
        For i = 0 To dgv.ColumnCount - 1
            clmns &= dgv.Columns(i).HeaderText.ToString().Replace(";", ",") & ";"
        Next
        outFile.WriteLine(clmns)
        For i = 0 To dgv.RowCount - 1
            clmns = ""
            For j = 0 To dgv.ColumnCount - 1
                clmns &= dgv(j, i).Value.ToString().Replace(";", ",") & ";"
            Next
            outFile.WriteLine(clmns)
        Next
        outFile.Close()

        p.StartInfo.FileName = "Excel.exe"
        p.StartInfo.Arguments = fn
        p.EnableRaisingEvents = True
        p.Start()
        AddHandler p.Exited, AddressOf cleartmp 'Löscht die Temp-Dateien
    End Sub
    Private WithEvents p As New Process

    Sub cleartmp(ByVal sender As System.Object, ByVal e As System.EventArgs) 'Nach Beenden des Programmes werden alle temporären Dateien gelöscht
        For Each file As String In IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Personal) & "\VERAG\Monitoring\tmp\") ' Ermittelt alle Dateien des Ordners 
            Try
                My.Computer.FileSystem.DeleteFile(file)
            Catch ex As Exception : End Try
        Next
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        genCSV_startWithExcel(dgv1)
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        genCSV_startWithExcel(dgv2)
    End Sub

    Private Sub frmShowDataDouble_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub
End Class