DownLoad Selected columns data from DataTable to CSV File

Here is the source code for downloading selected columns from DataTable to CSV file.

using System; 
using System.IO; 
using System.Collections; 
using System.Configuration; 
using System.Data; 
using System.Data.SqlClient; 
using System.Linq; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.HtmlControls; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Xml.Linq; 
public partial class RecordDownLoad : System.Web.UI.Page 
{ 
//Connection string for Test server 
public string ConnectionString = ConfigurationManager.
ConnectionStrings
["MyConnectionString"].ToString(); 
protected void Page_Load(object sender, EventArgs e) 
{ 
} 
/// <summary> 
/// Get data 
/// </summary> 
/// <returns>DataTable of records</returns> 
private DataTable Search() 
{ 
SqlConnection con = new SqlConnection(ConnectionString); 
SqlCommand cmd = new SqlCommand("spSearchRecords", con); 
cmd.CommandType = CommandType.StoredProcedure; 
//Pass search criteria with parameters 
cmd.Parameters.AddWithValue("@UserId", 
Convert.ToString(Session["Id"])); 
//Few more parameters from Session stored search criteria here 
//Data adapter 
SqlDataAdapter adapter = new SqlDataAdapter(cmd); 
DataTable dtResults = new DataTable(); 
DataSet ds = new DataSet(); 
//fill the data table with results 
adapter.Fill(dtResults); 
return dtResults; 
} 
/// <summary> 
/// Process download as CSV 
/// </summary> 
/// <param name="sender"></param> 
/// <param name="e"></param> 
protected void btnDownload_Click(object sender, EventArgs e) 
{ 
Response.ContentType = "text/csv"; 
Response.AddHeader("Content-Disposition", 
"Attachment;filename=Sample.csv"); 
//Get columns 
foreach (ListItem li in chkList.Items) 
{ 
if (li.Selected) 
{ 
Response.Write(li.Text + ","); 
} 
} 
Response.Write(Environment.NewLine); 
DataTable dt = Search(); 
//Rows 
foreach (DataRow row in dt.Rows) 
{ 
foreach (ListItem li in chkList.Items) 
{ 
if (li.Selected) 
{ 
Response.Write(row[li.Value].ToString() + ","); 
} 
} 
Response.Write(Environment.NewLine); 
} 
Response.End(); 
} 
}

No Comments