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

How can I export the data from datagrid to Excel using Visual Basic?

P: n/a
Hi, I am new to visual basic.
In my vb system, there is a dynamic datagrid to represent different reocrds in our database. Today I am gonna export the data to Excel file. I found most examples code in Google but all didn't work. Does anyone can help me? I am using visual basic 2010. I dont know how can get the value of the cells in the datagrid and the number of rows of the datagrid. Thanks everyone!
Nov 17 '10 #1
Share this Question
Share on Google+
2 Replies

Expert Mod 15k+
P: 31,426
Access can export its objects directly into Excel format. There doesn't appear to be any reason to know what rows and columns are included from your question.
Nov 17 '10 #2

P: 33
A simple way would be exporting it to a tab-delimited text file, and just importing that into excel. Here's some code that will export to tab or csv depending on parameters.

Expand|Select|Wrap|Line Numbers
  1.    Sub DataTable2Tab(ByVal table As System.Data.DataTable, ByVal filename As String, _
  2.     ByVal sepChar As String)
  3.         Dim writer As System.IO.StreamWriter
  4.         Try
  5.             writer = New System.IO.StreamWriter(filename)
  7.             ' first write a line with the columns name
  8.             Dim sep As String = ""
  9.             Dim builder As New System.Text.StringBuilder
  10.             For Each col As DataColumn In table.Columns
  11.                 builder.Append(sep).Append(col.ColumnName)
  12.                 sep = sepChar
  13.             Next
  14.             writer.WriteLine(builder.ToString())
  16.             ' then write all the rows
  17.             For Each row As DataRow In table.Rows
  18.                 sep = ""
  19.                 builder = New System.Text.StringBuilder
  21.                 For Each col As DataColumn In table.Columns
  22.                     builder.Append(sep).Append(row(col.ColumnName))
  23.                     sep = sepChar
  24.                 Next
  25.                 writer.WriteLine(builder.ToString())
  26.             Next
  27.         Finally
  28.             If Not writer Is Nothing Then writer.Close()
  29.         End Try
  30.     End Sub
You can call it like this:
Expand|Select|Wrap|Line Numbers
  1. DataTable2Tab(finalTable, filePath, vbTab)
Nov 17 '10 #3

Post your reply

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