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

Posted On
January 4, 2008 by Ramesh K
Language:

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 connectioncommand.Connection.Open();//create the sqldataadapter that would hold the result setSqlDataAdapter sqlAdapter = new SqlDataAdapter(command);//create our datatableDataTable dataTable = new DataTable();//fill the datatable with the values fetched from our querysqlAdapter.Fill(dataTable);//set the content type of the file to be downloadedHttpContext.Current.Response.ContentType = "Application/x-msexcel";//add the response headersHttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName+ "\"");//add the contents of the result set to the response stream and generate our csv fileHttpContext.Current.Response.Write(ToCSV(dataTable) );//close the connectioncommand.Connection.Close();//end the http responseHttpContext.Current.Response.End();}