Serving HTML tables as Excel 1

Posted by unixmonkey on September 22, 2010

Did you know that Excel can open a plain-old HTML table file and treat it just like a native Microsoft XLS file?

I’ve been doing this for ages, and its quite simple to pull off; just name your file something.xls and send the html with the content-type of “application/vnd.ms-excel” (and even that is not strictly required).

Even functions are somewhat supported like so.

<table>
  <tr>
    <td>2</td>
    <td>3</td>
    <td>=sum(a1:b1)</td>
  </tr>
</table>

However, there are a few drawbacks to this worth sharing when trying to style the tables with CSS.

1) Multiple class names are not supported:

<style type='text/css'>
  td.foo { background-color: red; }
</style>
<td class='foo bar'></td>

Will not apply the background color. You have to use only a single class per element like so:

<style type='text/css'>
  td.foo { background-color: red; }
</style>
<td class='foo'></td>

2) Descendant selectors are not supported:

<style type='text/css'>
  tr.odd td { background-color: red; }
</style>
<tr class='odd'>
  <td></td>
</tr>

Will not apply the background color either. You will have to be very specific about the element you want to style.

3) Certain colors and properties don't work:
If you use a color like #ECECEC (a light gray), it will come out white, If you use #CCCCCC (a darker gray) it will work. Stick to the basics like #000000 (black) if you can.

4) You'll have to add your styles either inline or in an html <style> block.
This shouldn't come as a surprise, but linking to an external stylesheet won't work. Excel won't reach out to your server to style the content.

5) Granularity will not be easily achieved:
Styling something with a 1px border is going to translate into a .5pt border. That's just how Excel rolls I guess.

Try marking up an Excel workbook and using 'save as' -> 'html' and opening up the file to checkout the markup Excel uses. This can give you some clues to what is acceptable.

I hope these simple tips help someone in a similar situation, and keep them from using a heavy arcane library to generate excel files with some added styling.