2
Contributors
1
Reply
2
Views
9 Years
Discussion Span
Last Post by Teme64
0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.