Tuesday, March 23, 2010

Export GridView to Excel

DataSet ds = new DataSet();
GridView gv = new GridView();
gv.DataSource = ds;
gv.AllowPaging = false;
gv.DataBind();

Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
gv.RenderControl(htmlWrite);

Response.Write(stringWrite.ToString());
Response.End();

There are some limitation on the above method.

the limitations of having to turn off event validation or override any page methods. This gives the freedom to put these methods were you want them ( within a static GridViewExportUtil class) without having to worry about the page that hosts the GridView doing anything special.


http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html

Monday, March 22, 2010

C# Formating

Date Formating:

DateTime rightnow = DateTime.Now;

string s= rightNow.ToString("MMM dd, yyyy")
string s = String.Format("{0:d}", rightNow)

Currency Formating:

string s = String.Format("{0:c}", price)

SQL db - use decimal(9, 2) for currency


If we wanted to format multiple variables in one shot we could do so:

s = String.Format("{0:c} on {1:d}", price, rightNow)