Friday, July 10, 2009

crrating csv in c# and asp.net

public void getHBRemindercsvFile()
{
if(dsBdayReminder.Tables[0].Rows.Count<1)
{
LblError.Visible=true;
LblError.Text="You have no reminders !";
}
string attachment = "attachment; filename=BirthdayReminder.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");
WriteColumnName(" Name , Day , Month ");
foreach (DataRow drt in dsBdayReminder.Tables[0].Rows)
{
WriteHBReminder(drt);
}

HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
private void WriteHBReminder(DataRow drt)
{
StringBuilder stringBuilder = new StringBuilder();

AddComma(drt["reminder_name"].ToString(), stringBuilder);
AddComma(drt["reminder_day"].ToString(), stringBuilder);
AddComma(GetMonthName(Convert.ToInt32(drt["reminder_month"])), stringBuilder);

HttpContext.Current.Response.Write(stringBuilder.ToString());
HttpContext.Current.Response.Write(Environment.NewLine);
}

private void AddComma(string value, StringBuilder stringBuilder)
{
stringBuilder.Append(value.Replace(',', ' '));
stringBuilder.Append(", ");
}

private void WriteColumnName(string columnNames)
{
HttpContext.Current.Response.Write(columnNames);
HttpContext.Current.Response.Write(Environment.NewLine);
}

No comments: