Excel Export, the Stupid Simple Way
It occurred to me the other night while helping Mike figure out how to prepare some reports in Excel from a Rails application that it probably wasn’t necessary to use the plugin I created. One of the big drawbacks to the Excel Export plugin is that it doesn’t currently support formatting of cells. (There just really isn’t a good way to do that.) One trick I’ve known about for years is the ability for Excel to read in an HTML table of data and render it as a spreadsheet.
This meant that we could simple create a new view that contained the HTML table
<table border="1" id="doc"> <tr> <td>Last Name</td> <td>First Name</td> <td>Birthday</td> <td>Email</td> </tr> <tr> <td><%=user.last_name %></td> <td><%=user.first_name %></td> <td><%=user.birthday %></td> <td><%=user.email %></td> </tr> </table>
Then it’s just a simple matter of making a controller action to display that view.
def export headers[’Content-Type’] = “application/vnd.ms-excel” render :layout=> false end
That should cause the browser to open Excel, instead of displaying the page. Now, I can’t guarantee that this will work on Linux, OSX, or anywhere where Excel is not installed. However it certainly meets our needs for this one project and so I t hought I would share it with everyone else.
