C# Snippet that Always has a Place in Business
2007 09 07 – 7:33 amWith a title so profound you probably think that this is going to be an enormously complicated little slice of code. We’ll see…
In business one thing nearly every analyst type, accounting type and manager type needs to see quantitative data represented in table format. Often times, they even want to manipulate that data through their analysis of it. As a developer, you must report data to the user (those types mentioned above) and how better to do that than to give them the ability to save a file off in Excel format containing the record set they need? Enter my snippet…
protected void ExcelExport() {
Response.Clear();
Response.AddHeader("content-disposition",
"attachment;filename=caberecsearch.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite =
new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
// Set formatting to something Excel friendly
GridView1.RowStyle.BackColor =
System.Drawing.Color.WhiteSmoke;
GridView1.RowStyle.HorizontalAlign =
HorizontalAlign.NotSet;
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End(); }
public override void VerifyRenderingInServerForm(Control control) {
// Confirms that an HtmlForm control is rendered for the
// specified ASP.NET server control at run time. }
I guess its actually two methodes. As of .Net 2.0 the VerifyRenderingInServerForm() override needs to be in there as well.
Often times, I find myself not using the GridView control to represent tabular data. Working at a Section 508 compliant shop, we tend make a lot of our own xhtml rather than let .Net do it. But, that doesn’t mean you can’t hide a gridview with this data and generate your excel file from it view a button to execute the above method.
A professional software developer on the .Net and LAMP platforms.
I enjoy walks on the beach, SQL Server, video games, and college sports.