By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,963 Members | 2,490 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,963 IT Pros & Developers. It's quick & easy.

how can I export datagridview to Excel

P: 3
Expand|Select|Wrap|Line Numbers
  1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  2.         DATAGRIDVIEW_TO_EXCEL((DataGridView1)) ' PARAMETER: YOUR DATAGRIDVIEW
  3.     End Sub
  4.  
  5.     Private Sub DATAGRIDVIEW_TO_EXCEL(ByVal DGV As DataGridView)
  6.         Try
  7.             Dim DTB = New DataTable, RWS As Integer, CLS As Integer
  8.  
  9.             For CLS = 0 To DGV.ColumnCount - 1 ' COLUMNS OF DTB
  10.                 DTB.Columns.Add(DGV.Columns(CLS).Name.ToString)
  11.             Next
  12.  
  13.             Dim DRW As DataRow
  14.  
  15.             For RWS = 0 To DGV.Rows.Count - 1 ' FILL DTB WITH DATAGRIDVIEW
  16.                 DRW = DTB.NewRow
  17.  
  18.                 For CLS = 0 To DGV.ColumnCount - 1
  19.                         If DGV.Columns(CLS).Visible = True Then
  20.  
  21.                         Try
  22.                             DRW(DTB.Columns(CLS).ColumnName.ToString) = DGV.Rows(RWS).Cells(CLS).Value.ToString
  23.                         Catch ex As Exception
  24.  
  25.                         End Try
  26.                     End If
  27.                 Next
  28.  
  29.                 DTB.Rows.Add(DRW)
  30.             Next
  31.  
  32.             DTB.AcceptChanges()
  33.  
  34.             Dim DST As New DataSet
  35.             DST.Tables.Add(DTB)
  36.             Dim FLE As String = "" ' PATH AND FILE NAME WHERE THE XML WIL BE CREATED (EXEMPLE: C:\REPS\XML.xml)
  37.             DTB.WriteXml(FLE)
  38.             Dim EXL As String = "" ' PATH OF/ EXCEL.EXE IN YOUR MICROSOFT OFFICE
  39.             Shell(Chr(34) & EXL & Chr(34) & " " & Chr(34) & FLE & Chr(34), vbNormalFocus) ' OPEN XML WITH EXCEL
  40.  
  41.         Catch ex As Exception
  42.             MsgBox(ex.ToString)
  43.         End Try
  44.  
  45.     End Sub
Feb 7 '14 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.