Giving the user what they want!
[UPDATE]
Scott
pointed out the the fact that you can force file names
in a download using content-disposition. This is
probably the easiest way but the solution listed below
will allow you to call to files that do not exists; ie
KentuckyThirdDistrict.xls?querystringcrap and the file
will download as KentuckyThirdDistrict. Oh well, I did
it the hard way :)
Sometimes a little feature can give quite a bit of effort to your site in style points. Take for instance data grids and excel documents. This is a common thing now, to take a data grid and give it to the user as an excel document. Some people are even trying to sell products doing this but by and large it is simple enough that most people will just roll their own.
It is quite simple…
Create instances of a DataGrid, StringWrtier and
HtmlWriter
Set the response content type to
"application/vnd.ms-excel"
Render the grid to the HtmlTextWriter
Reponse.Write the StringWriter data to the
client.
This is all well and good except for the fact that of your user chooses to save to disk, they have an ASPX file. For the purposes of this lesson we will go ahead and assume the obvious and state that all users are stupid and will not pay attention to the file extension wonder why their excel document will not open in excel when they double click it!
HttpHandlers to the rescue!
After one to many stupid users double clicking the aspx file with great confusion I conjoured up the idea of using an HttpHander to give the file the proper extension when the user saved it to disk.
It is also quite simple…
Create a class that implements
System.Web.IHttpHandler
Code up the ProcessRequest method with your data
grid rendering code (see above)
Create entries in your web.config and IIS metabase
to support your new handler for .xls files
The really cool part about this scenario is that you can code the call just like a call to an aspx file, using querystring parameters and all!
Here is an example…
public void
ProcessRequest(System.Web.HttpContext context)
{
DataGrid
Grid = new
DataGrid();
StringWriter oStringWriter = new
StringWriter();
HtmlTextWriter
oHtmlTextWriter = new
HtmlTextWriter(oStringWriter);
context.Response.Clear();
context.Response.Buffer
= true;
context.Response.ContentType =
"application/vnd.ms-excel";
context.Response.ContentEncoding
= System.Text.Encoding.Default;
//Little diddy I do to get a data table
instance
Grid.DataSource = EmployerData.Get(context);
Grid.DataBind();
Grid.RenderControl(oHtmlTextWriter);
context.Response.Write(oStringWriter.ToString());
context.Response.End();
}
So once again boys and girls, give your users what they want! If they want excel; go the extra mile and give it to em!