.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Melody Anderson

Home >> Code Snippets >> DataGrid >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Export csv data from DataGridView in windows application

Posted By:Faizal       Posted Date: May 14, 2013    Points: 40    Category: DataGrid    URL: http://www.dotnetspark.com  

Code example to export DataGridView Data to csv (comma separated value) format in C# and VB.NET. Hope this will help all who would like to extract data in any event

Below Code sample is can be used to export data from DataGridView in windows application. In this code LINQ also been used to extract data from DataGridView. We will see both code exaple in C# and VB.Net both.

Don't forget to add following namespace System.IO for to create file or file operation and System.Text for StringBuilder class.

C# Code example

//Create header
var headers = myDataGridView.Columns.Cast<DataGridViewColumn>( );
sb.Append( string.Join( "," , headers.Select( column => "\"" + column.HeaderText + "\"" ) ) );
sb.AppendLine( );

// Get values
foreach( DataGridViewRow row in myDataGridView.Rows )
    var cellsValues = row.Cells.Cast<DataGridViewCell>( );
    sb.Append( string.Join( "," , cellsValues.Select( cell => "\"" + cell.Value + "\"" ) ) );
    sb.AppendLine( );

string dataToExport = sb.ToString( );
if( !string.IsNullOrEmpty( dataToExport ) )
    //Save the CSV string to a file using streamWriter
    using( StreamWriter sr = new StreamWriter( @"c:\temp\data.csv" , false ) )
        sr.Write( dataToExport );
        sr.Flush( );
        sr.Close( );// Close file
        MessageBox.Show( "Data Exported successfully!" );


VB.Net code sample

'Create header
Dim headers = myDataGridView.Columns.Cast(Of DataGridViewColumn)()
sb.Append(String.Join(",", headers.[Select](Function(column) """" + column.HeaderText + """")))

' Get values
For Each row As DataGridViewRow In myDataGridView.Rows
	Dim cellsValues = row.Cells.Cast(Of DataGridViewCell)()
	sb.Append(String.Join(",", cellsValues.[Select](Function(cell) """" + cell.Value + """")))

Dim dataToExport As String = sb.ToString()
If Not String.IsNullOrEmpty(dataToExport) Then
	'Save the CSV string to a file using streamWriter
	Using sr As New StreamWriter("c:\temp\data.csv", False)
		' Close file
		MessageBox.Show("Data Exported successfully!")
	End Using
End If


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend