Ive bin looking for some code to export the contents of a DataGridView to CSV so I can view it in Excel.

I found this but ive got errors;

Dim sr As StreamWriter = File.CreateText(strExportFileName)
        Dim strDelimiter As String = strDelimiterType
        Dim intColumnCount As Integer = DataGridView.Columns.Count - 1
        Dim strRowData As String = ""

        If blnWriteColumnHeaderNames Then
            For intX As Integer = 0 To intColumnCount
                strRowData += Replace(DataGridView.Columns(intX).Name, strDelimiter, "") & _
                IIf(intX < intColumnCount, strDelimiter, "")
            Next intX
            sr.WriteLine(strRowData)
        End If

        For intX As Integer = 0 To DataGridView.Rows.Count - 1

            strRowData = ""

            For intRowData As Integer = 0 To intColumnCount
                strRowData += Replace(DataGridView.Rows(intX).Cells(intRowData).Value, strDelimiter, "") & _
                    IIf(intRowData < intColumnCount, strDelimiter, "")
            Next intRowData

            sr.WriteLine(strRowData)

        Next intX
        sr.Close()
        MsgBox("saved!")

Recommended Answers

All 8 Replies

Hi,

What errors do you have?

Its sorted now, but please could you show me how to show the column headers in the CSV. And When I import it, it not import the column names.

Imports System.IO
Public Class driverdatabase

    Private Sub subExportDGVToCSV(ByVal strExportFileName As String, ByVal DataGridView As DataGridView, Optional ByVal blnWriteColumnHeaderNames As Boolean = False, Optional ByVal strDelimiterType As String = ",")
        Dim sr As StreamWriter = File.CreateText(strExportFileName)
        Dim strDelimiter As String = strDelimiterType
        Dim intColumnCount As Integer = DataGridView.Columns.Count - 1
        Dim strRowData As String = ""

        If blnWriteColumnHeaderNames Then
            For intX As Integer = 0 To intColumnCount
                strRowData += Replace(DataGridView.Columns(intX).Name, strDelimiter, "") & _
                IIf(intX < intColumnCount, strDelimiter, "")
            Next intX
            sr.WriteLine(strRowData)
        End If

        For intX As Integer = 0 To DataGridView.Rows.Count - 1

            strRowData = ""

            For intRowData As Integer = 0 To intColumnCount
                strRowData += Replace(DataGridView.Rows(intX).Cells(intRowData).Value, strDelimiter, "") & _
                    IIf(intRowData < intColumnCount, strDelimiter, "")
            Next intRowData

            sr.WriteLine(strRowData)

        Next intX
        sr.Close()
        MsgBox("saved!")

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Call subExportDGVToCSV(My.Computer.FileSystem.SpecialDirectories.Desktop & "\driversdatabase.csv", Me.driversGrid, False, ",")
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim fName As String = ""
        OpenFileDialog1.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.Desktop
        OpenFileDialog1.Filter = "CSV files (*.csv)|*.CSV"
        OpenFileDialog1.FilterIndex = 2
        OpenFileDialog1.RestoreDirectory = True
        If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
            fName = OpenFileDialog1.FileName
        End If
        Dim TextLine As String = ""
        Dim SplitLine() As String


        If System.IO.File.Exists(fName) = True Then
            Dim objReader As New System.IO.StreamReader(fName)
            Do While objReader.Peek() <> -1
                TextLine = objReader.ReadLine()
                SplitLine = Split(TextLine, ",")
                Me.driversGrid.Rows.Add(SplitLine)
            Loop
        Else
            MsgBox("File Does Not Exist")
        End If
    End Sub

End Class

Ok, I did the whole code you wanted. The code can Export and Import data from CS file.
It even creates columnHeader text:

Public Partial Class Form1
	Inherits Form
	Public Sub New()
		InitializeComponent()

		'creating columns:
		dataGridView1.Columns.Add("col1", "Id")
		dataGridView1.Columns.Add("col2", "Name")
		'allowing that user can add new rows:
		dataGridView1.AllowUserToAddRows = True
	End Sub

	Private Sub buttonSave_Click(sender As Object, e As EventArgs)
		Dim filePath As String = "C:\1\testCSV2.csv"
		Dim delimiter As String = ";"
		Dim sb As New StringBuilder()
		'create columnNames:
		For i As Integer = 0 To dataGridView1.Rows.Count - 1
			Dim array As String() = New String(dataGridView1.Columns.Count - 1) {}

			If i.Equals(0) Then
				'get column header text from all columns:
				For j As Integer = 0 To dataGridView1.Columns.Count - 1
					array(j) = dataGridView1.Columns(j).HeaderText
				Next
				sb.AppendLine([String].Join(delimiter, array))
			End If

			'get values from columns for specific row (row[i]):
			For j As Integer = 0 To dataGridView1.Columns.Count - 1
				If Not dataGridView1.Rows(i).IsNewRow Then
					array(j) = dataGridView1(j, i).Value.ToString()
				End If
			Next
			If Not dataGridView1.Rows(i).IsNewRow Then
				sb.AppendLine([String].Join(delimiter, array))
			End If
		Next
		File.WriteAllText(filePath, sb.ToString())
	End Sub

	Private Sub buttonLoad_Click(sender As Object, e As EventArgs)
		Dim filePath As String = "C:\1\testCSV2.csv"
		Dim delimiter As String = ";"
		Dim rows As String() = File.ReadAllLines(filePath)
		'clear DGV:
		dataGridView1.Rows.Clear()
		'removing columns, because they will be created ones again
		'this is a protection becuase I dont know what will you do 1st (or import or export data)!!
		Dim list As New List(Of String)()
		For Each col As DataGridViewColumn In dataGridView1.Columns
			list.Add(col.Name)
		Next
		For Each _col As String In list
			dataGridView1.Columns.Remove(_col)
		Next

		'populate DGV:
		For i As Integer = 0 To rows.Length - 1
			Dim columns As String() = rows(i).Split(New String() {delimiter}, StringSplitOptions.RemoveEmptyEntries)
			If i.Equals(0) Then
				For j As Integer = 0 To columns.Length - 1
					dataGridView1.Columns.Add("col" & (j + 1), columns(j))
				Next
			Else
				dataGridView1.Rows.Add()
				For j As Integer = 0 To columns.Length - 1
					dataGridView1(j, i - 1).Value = columns(j)
				Next
			End If
		Next
	End Sub
End Class

Thanks but i get a few errors:

When Trying to Export

Object reference not set to an instance of an object.
array(j) = datagridview1(j, i).Value.ToString()

hi all..

i did want to ask something
when i copy paste the whole code.. i get this..

Dim sb As New StringBuilder() >>> type 'StringBuilder' is not defined

can anyone help me please ??

hi all..

i did want to ask something
when i copy paste the whole code.. i get this..

Dim sb As New StringBuilder() >>> type 'StringBuilder' is not defined

can anyone help me please ??

Hi,

You need to add the proper namespace.

Imports System.Text

thanks,

but after I try to run it .. I get this error " Object reference not set to an instance of an object.
array(j) = datagridview1(j, i).Value.ToString() "

anyone can help me?

@Christoven

Please create a new thread to post your question and also post code part and csv file content.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.