in vb.net how to export data from datagridview to excel

If you don't need to export directly to native xls-file, one way is to use CSV-file:

Dim OutFile As StringBuilder
Dim SepChar As String
Dim i As Integer
Dim j As Integer

OutFile = New StringBuilder()
SepChar = ","
For i = 0 To DataGridView1.RowCount - 1
  ' Columns of one row
  For j = 0 To DataGridView1.ColumnCount - 1
    If DataGridView1.Item(j, i).ToString.IndexOf(SepChar) >= 0 Then
      ' Contains sepchar, add quotes
      OutFile.Append("'")
      OutFile.Append(DataGridView1.Item(j, i).ToString)
      OutFile.Append("'")
    Else
      OutFile.Append(DataGridView1.Item(j, i).ToString)
    End If
    OutFile.Append(SepChar)
  Next j
  OutFile.AppendLine()
Next i
My.Computer.FileSystem.WriteAllText("C:\test.csv", OutFile.ToString, False)

Just loop cols and rows, separate each item with comma, insert newline after each row and write to csv-file. If comma doesn't work, change SepChar = ";" i.e. use semicolon.
Now when you open this csv-file with Excel it parses file to rows and cols.

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.