ioSamurai ioSamurai - 2 months ago 13
ASP.NET (C#) Question

Easy method of exporting an html table to excel file in ASP.NET?

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.

Answer

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.