Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Export to Excel from DataGrid in Windows Application 1

Status
Not open for further replies.

shack623

Programmer
Aug 11, 2001
12
US
I have a windows application with several forms that contain DataGrid controls. The user wants to be able to select/highlight desired rows and right-click, or simply right-click anywhere within the DataGrid and have the DataGrid contents exported to MS Excel or saved into a CSV file. I noticed most of the threads addressing this topic apply to web-based applications. Can anyone advise me how to accomplish this task for a windows-based application?
 
You can export the data grid contents to a CSV file with the following:
Code:
Dim dt As System.Data.DataTable = CType(DataGrid1.DataSource, System.Data.DataTable)

Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter("C:\Test.csv")

Dim dr As System.Data.DataRow, i As Int32

Dim s(dt.Columns.Count - 1) As String

For Each dr In dt.Rows

    For i = 0 To s.GetUpperBound(0)

        s(i) = dr(i).ToString()

    Next

    sw.WriteLine(String.Join(",", s))

Next

sw.Close()
 
Ive been playing with xml and data grids, the nice thing about it is excel can open xml and it looks really good.
try xmlwrite.
<code>
Dim filename As String
filename = "c:\xmldata\projects.xml"
DataGrid1.DataSource.WriteXml(filename)
</code>

if it is to be it's up to me
 
inifnitelo is right, however be aware of the following caveats:

1. The WriteXml method will only work if the datagrid datasource is a dataset, or the datasource is moved into a dataset.

2. Not all versions of Excel support XML properly (XL97 doesn't, for example).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top