Programming, Technology, Web Development, Whatever
Exporting to Excel using ColdFusion
Sometimes you’ll have a query that you want your users to be able to export to an Excel file. If you have ColdFusion 9, you could use the cfspreadsheet tag to do this, however ColdFusion 8 users and below don’t have this luxury. Fortunately the workaround isn’t all too bad. Here’s what you do:
<cfcontent type="application/msexcel"> <cfheader name="Content-Disposition" value="filename=myFile.xls"> <table> <tr><!-- A row --> <td>A Cell</td> </tr> </table> </cfcontent>
That’s all there is to it. Basically you format the spreadsheet using HTML for a table. You can also format the cells using CSS, although results vary by which version of Excel or Open Office Spreadsheet your using. Office 2007 and 2010 allow for more customization using CSS than 2003 does, but for the most part generating simple spreadsheets using this method works pretty well. For example if I wanted to change the background color and set up a 3 column table with a header:
<cfcontent type="application/msexcel"> <cfheader name="Content-Disposition" value="filename=myFile.xls"> <table style="background-color:#366092; color:#FFFFFF;"> <tr><!-- Header Row--> <td colspan="3" style="font-size:15px;">This is a header</td> </tr> <tr> <td>A Cell</td> <td>A Cell</td> <td>A Cell</td> </tr> <tr> <td>A Cell</td> <td>A Cell</td> <td>A Cell</td> </tr> </table> </cfcontent>
Which yields:

Excel 2010
Just remember to use cfoutput when exporting ColdFusion data.
| Print article | This entry was posted by Nathan on December 19, 2009 at 9:40 PM, and is filed under ColdFusion. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 8 months ago
just a small nit-pick but probably should add charset=”utf-8″ to both cfcontent & cfheader to keep the encoding clear.