Export DataSet to CSV

CodeKeep C# Feed Aprile 30th, 2008

Description: Download a CSV file from an ASP.Net page. Just call the method from any button click.

Link: http://www.codekeep.net/snippets/aa3d04d0-ec11-47bd-86e6-00373e57fcf2.aspx

private void downloadCSV(DataSet ds, string filename)
{
	Response.Clear();
	Response.ContentType = "text/plain";
	Response.AppendHeader("content-disposition",
												"attachment; filename=" + filename + ".csv");
	Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);

	DataTable table = ds.Tables[0];

	//Write the column headers
	bool first = true;
	foreach (DataColumn column in table.Columns)
	{
		if (!first)
		{
			Response.Write(",");
		}
		Response.Write("\"");
		Response.Write(column.ColumnName);
		Response.Write("\"");
		first = false;
	}

	//Write the data
	foreach (DataRow row in table.Rows)
	{
		Response.Write(Environment.NewLine);
		first = true;
		foreach (DataColumn column in table.Columns)
		{
			if (!first)
			{
				Response.Write(",");
			}
			Response.Write("\"");
			Response.Write(row[column.ColumnName]);
			Response.Write("\"");
			first = false;
		}
		Response.Write(Environment.NewLine);
	}

	Response.Flush();
	Response.End();
}

  • .NET
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Comments are closed.

Trackback URI |