Compartir a través de


Printing DataGridView contents in CSV format

 

 

While answering questions on the windowsforms.net regarding datagridview, i noticed that a good number of people wanted to store the contents of the datagridview in a csv (comma separated value format).

 

In this blog, i am just writing a simple solution for this. We do this by printing each row of the Datagridview.

 

The following block of code in VB accomplishes this task. DataGridView1 has to be stored in the csv format.

 

        Dim numCols As Integer = DataGridView1.ColumnCount

        Dim numRows As Integer = DataGridView1.RowCount - 1

        Dim strDestinationFile As String = "c:\\output.txt"

        Using tw As TextWriter = New StreamWriter(strDestinationFile)

            'writing the header

            For indexCols As Integer = 0 To numCols - 1

  tw.Write(DataGridView1.Columns(indexCols).HeaderText)

                If (indexCols <> numCols - 1) Then

                    tw.Write(", ")

                End If

            Next

            tw.WriteLine()

            'writing the data

   For indexRows As Integer = 0 To numRows - 1

                'print all column values for a row

                For indexCols As Integer = 0 To numCols - 1

                    tw.Write(DataGridView1.Rows(indexRows).Cells(indexCols).Value)

                    If (indexCols <> numCols) Then

                        tw.Write(", ")

                    End If

                Next

                tw.WriteLine()

            Next

        End Using

 

Also, in the above code you can notice usage of Using block. Not only does Using intialize the resource but also disposes it. If I were not making use of Using block, here, I can also accomplish this by a try catch finally block as follows.

        Dim tw As TextWriter

        Try

            tw = New StreamWriter(strDestinationFile)

            --------

            -------

        Catch ex As Exception

        Finally

            tw.Close()

        End Try

 

We can see that making use of Using block makes the code look less cumbersome and this is a very good feature in .Net

Comments

  • Anonymous
    June 20, 2007
    Thank You,  this was copy paste and worked great.

  • Anonymous
    March 02, 2008
    This simplistic solution doesn't work in cases where a datagridview cell value contains embedded commas -- for example: June 12, 1958 will be written as June 12, 1958, and the value will appear in two columns! Audi

  • Anonymous
    December 18, 2014
    I am using Visual Basic 6.0 I have made my project but unable to connect a printer with V.B. means when I tried to get a print from my project on a paper its show error even my printer works in other applications. Regards airshaft.org