CSV file from a database using asp.net with C#


By following this code, you can achieve the desired result. I have written this code using C# with asp.net.



public void genrateCsv(string strQuery,string fileName)
{
SqlCommand command = new SqlCommand(strQuery,sqlConn);
//open the connection
command.Connection.Open();
//create the sqldataadapter that would hold the result set
SqlDataAdapter sqlAdapter = new SqlDataAdapter(command);
//create our datatable
DataTable dataTable = new DataTable();
//fill the datatable with the values fetched from our query
sqlAdapter.Fill(dataTable);
//set the content type of the file to be downloaded
HttpContext.Current.Response.ContentType = "Application/x-msexcel";
//add the response headers
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName+ "\"");
//add the contents of the result set to the response stream and generate our csv file
HttpContext.Current.Response.Write(ToCSV(dataTable) );
//close the connection
command.Connection.Close();
//end the http response
HttpContext.Current.Response.End();
}




Added on January 4, 2008 Comment
}