Home
Products
Forums
Help
Publish Article
Go Freelance

Export ASP.Net DataGrid DataSet To CSV File

In this article we will present a very useful utility function that can be used to export a data table to a comma separated values (CSV) file. The code first loops through the columns of the data table to export the names of all the data columns. And then in next loop the code iterates over each data row to export all the values in the table. The code represents an event handler that is present on the ASPX page. When user clicks on the button, the data gets exported to GridData.txt file. Once the data is exported is file, you can stream it to the use's browser.

private void OnExportGridToCSV(object sender, System.EventArgs e)
{
	// Create the CSV file to which grid data will be exported.
	StreamWriter sw = new StreamWriter(Server.MapPath("~/GridData.txt"), false);
	// First we will write the headers.
	DataTable dt = m_dsProducts.Tables[0];
	int iColCount = dt.Columns.Count;
	for(int i = 0; i < iColCount; i++)
	{
		sw.Write(dt.Columns[i]);
		if (i < iColCount - 1)
		{
			sw.Write(",");
		}
	}
	sw.Write(sw.NewLine);
	// Now write all the rows.
	foreach (DataRow dr in dt.Rows)
	{
		for (int i = 0; i < iColCount; i++)
		{
			if (!Convert.IsDBNull(dr[i]))
			{
				sw.Write(dr[i].ToString());
			}
			if ( i < iColCount - 1)
			{
				sw.Write(",");
			}
		}
		sw.Write(sw.NewLine);
	}
	sw.Close();
}
						

If you are looking into a technique on how to import a CSV file into a DataGrid or GridView, read the article How to import CSV file into Grid?.

Go Freelance
Home     About us     Contact us    Copyright    Privacy Policy    Return Policy    Advertisers
Copyright © Netomatix