How to export Datagridview1 contents in Vb.Net Windows form to Excel

searchsanjaysharma
searchsanjaysharma used Ask the Experts™
on
How to export the data in Datagridview1 in vb.net to excel.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Author

Commented:
Import Microsoft.

does comes in vb.net 2008
Commented:
Simply write the contents of the datagridview to a CSV file (which any version of Excel will hapilly open!)
Dim xBuilder As New List(Of String)
'first add the header
xBuilder.Add(String.Join(",", (From x As DataGridViewColumn In Me.DataGridView1.Columns Select x.HeaderText).ToList))
'then the data
For Each row As DataGridViewRow In Me.DataGridView1.Rows
    Dim line = (From cell As DataGridViewCell In row.Cells Select cell.Value).ToList
    xBuilder.Add(String.Join(",", line.ToArray))
Next
'finally save to file
File.WriteAllLines("PathToFile", xBuilder)

Open in new window

Author

Commented:
Correct this error

  Try
      Dim xlApp As Microsoft.O
      Dim xlWorkBook As Micros
      Dim xlWorkSheet As Micro
      Dim misValue As Object =
      Dim i As Integer
      Dim j As Integer

      xlApp = New Microsoft.Of
      xlWorkBook = xlApp.Workb
      xlWorkSheet = xlWorkBook

      For i = 0 To DataGridVie
          For j = 0 To DataGri
              xlWorkSheet.Cell
                  DataGridView
          Next
      Next

      xlWorkSheet.SaveAs("C:\v
      xlWorkBook.Close()
      xlApp.Quit()

      releaseObject(xlApp)
      releaseObject(xlWorkBook
      releaseObject(xlWorkShee

      MsgBox("You can find the
  Catch ex As Exception
      MsgBox(ex.ToString())
  End Try
d Sub

ivate Sub releaseObject(ByVal
  Try
      System.Runtime.InteropSe
      obj = Nothing
  Catch ex As Exception
      obj = Nothing
  Finally
      GC.Collect()
  End Try
End Sub

Exception attached in file
exception.docx
can you try to save the file in other location and try.
d:\

Author

Commented:
ok

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial