====== How to Serve HTML as an Excel File from a Web Application ====== Brendan Kidwell\\ [[brendan@glump.net]] 10 January 2008 It is possible to store HTML in a file named ".XLS" and then open that in Excel. This is useful for web applications that want to export data easily into a spreadsheet, as it's a lot easier than finding an Excel file handling library and programmatically creating an Excel binary file. This method allows you to: * Output the spreadsheet as almost plain HTML, allowing for easy programming * Use the Freeze Panes feature to freeze header rows and/or columns * Use merged cells * Include line breaks in cells ===== Skeleton ===== Create a new file with the ".XLS" extension and use this skeleton code to start: ** TABLE HEADER ROWS GO HERE ** ... ** TABLE DATA ROWS GO HERE ** ...
Header Cell
Data Cell
If you are **not** using the Freeze Panes feature, omit the six lines from "" to "". ===== Making the File Available on the Web Server ===== If the file is stored statically on the web server, make sure the server is configured to send the correct MIME type for the ".XLS" extention, which is "application/msexcel". If you are generating the file dynamically as the output of a script, make sure to send this MIME type in the HTTP headers before your script outputs the body of the file. Also you should include the Content-Disposition header to instruct the browser to download the file and how to name it: Content-Type: application/msexcel Content-Disposition: attachment; filename=NAMEOFWORKSHEET.xls ===== Styling Cells ===== Table header cells and data cells get certain default formatting (header: bold centered; data: normal left aligned). To add additional formatting, use the usual HTML tags like "B", "I", and "SPAN". Hyperlinks may be embedded in cells. To add a **line break** within a cell, use this code:
To **merge cells** together, do it as you normally would in an HTML table. Don't forget to include and omit the appropriate cells later in the row and in succeeding rows. For example, this code puts three cells in the a 2x2 block of cells: This cell is 2 rows high. cell 2 cell 3 ===== Example File ===== Here is an example file to play with: {{howto:example-html.xls|}} (You can read and edit this file in a text editor!) Screenshot:\\ {{howto:example-html.xls.png?400|}}