If you want a quick and dirty way to export some data to excel, you can use this nifty trick: generate an HTML file with a table containing the data, and change the file's extension to xls. And that's it! You'll open the file in excel.

You can also have a page rendering in excel using this trick. For exemple, if you're using ASP.NET, the following Page will start a download for a Report.xls file:

C#:
  1. public class ToExcel : Page {
  2.  
  3.     protected override void OnLoad(EventArgs e)
  4.     {
  5.         base.OnLoad(e);
  6.         Response.AddHeader("Content-disposition",
  7.             "attachment; filename=Report.xls");
  8.         Response.AddHeader("Content-type",
  9.             "excel/ms-excel; name=Report.xls");
  10.     }
  11.    
  12.     protected void Render(HtmlTextWriter writer)
  13.     {
  14.         writer.Write("<table>");
  15.         writer.Write("<tr>");
  16.         writer.Write("<td>Some</td>");
  17.         writer.Write("<td>Data</td>");
  18.         writer.Write("</tr>");
  19.         writer.Write("</table>");
  20.     }
  21.  
  22. };

Related Posts

3 Responses to “The easiest way to export to MS Excel”

  1. Tiago Sousa Says:

    In one word…BEAUTIFUL

  2. ASP.NET - Continuous Dynamic Downloading | Pedro Santos Says:

    [...] the The easiest way to export to MS Excel, I came across with another problem: if we make a request to download a big file, the server will [...]

  3. elliott Says:

    I don’t think this little trick works for OSX/Mac versions of MS Excel, unfortunately.