views:

752

answers:

2

Have a report generated from the DB, want to add an export button so they can get the same report in a excel readable sheet of some type. The key here is ease of implementation so a CSV is fine over XLS if it's easier.

A: 

You can use HtmlTextWriter:

  System.IO.StringWriter stringWriter = new System.IO.StringWriter();

  System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);

  grid.RenderControl(htmlWriter);

where grid is a DataGrid object. You can use other types of controls as well.

fbinder
+2  A: 

Excel is actually somewhat good at reading HTML. Espcially if your HTML contains just a single table. If you want to tell the browser to open the file up in excel, you can use

Response.ContentType = "application/vnd.ms-excel"

This tells the browser to open the document in Excel, instead of just rendering it by itself. There are a few problems though. I don't think it will work if somebody wants to open it with OO.org calc instead. Also, when trying to save it, it will never convert the file to a real excel file, unless the user explicity changes the file type. If it's just an intranet app for your organization, this may not be a problem. The plus side is, is that you can use colours, borders, and even formulas, which can't be done when using straight CSV.

Kibbee
I've done this in a very simple application, and it worked real well. Rather than messing with any sort of exporting or the such, it handled it all with one line of code.
MattGWagner